1

Running into an issue. In running the code below, I'm trying to replace a string of text that appears in an blog excerpt field with a clickable link.

jQuery(document).ready(function( $ ) {
    
    var elements = document.getElementsByClassName('post-excerpt');
    if (elements.length > 0) {
    
    $('.post-excerpt').html($('.post-excerpt').html().replace(/((http:|https:)[^\s]+[\w])/g,'<a href="$1" target="_blank">$1</a>'));
    }
    
});

The problem is that the link from the first except is being copied to all other buttons on the page. How do I modify the code above to make sure that it parses through each excerpt link UNIQUELY and replaces that string with an equivalent HTML link?

Blog page

0

1 Answer 1

3

I suppose what you need is an .each() loop:

jQuery(document).ready(function( $ ) {
    
    var elements = $('.post-excerpt')
    if (elements.length > 0) {
      elements.each(function(index,element){
        $(element).html($(element).html().replace(/((http:|https:)[^\s]+[\w])/g,'<a href="$1" target="_blank">$1</a>'));
      })
    }
});
Sign up to request clarification or add additional context in comments.

6 Comments

Fantastic, this is perfect! I thought it was the each() function, but wasn't sure how to apply it. Thank you!
By the way... The if statement is useless because if there is no .post-excerpt elements, the each loop just won't run. So you can remove it safely. ;)
Hello again. There's an issue with the above script. I'm adding it to a page that displays a number of blog post thumbnails with pagination. On the first page, the script loads correctly, and the text links are replaced with actual hyperlinks (and the View PDF as a button via CSS). However, when I navigate to the second page of results, the script no longer fires, and I see the actual hyperlink as a string. Is there a way to update the above so that the script continuously fires as I paginate?
The replacements are done when the DOMContentLoaded event fires. Now it should also run when your pagination is creating some new elements. So check if you have an event looking like "after pagination render" with the pagination plugin you have.
Did it by adding $( document ).ajaxComplete(function() { PDFScript(); }) and moving the above code into a function to call.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.