Bryce
Bryce

Reputation: 367

Add a link to certain text with jQuery, ignoring text that's already inside a link

I need to change all instances of "Express Entry" to "<a href="link">Express Entry</a>", ignoring any text that is already inside a link

This is what I have:

$('.news article p').each(function() {
    var text = $(this).html();
    if ( ignore anything wrapped in an <a> tag ) {
        $(this).html(text.replace('Express Entry', '<a href="https://www.ackahlaw.com/resources/check-your-express-entry-score">Express Entry</a>'));
    }
});

I've tried using contents() and nodeType, but can't quite figure out how to make it work...

Upvotes: 0

Views: 26

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

.contents() get the children of each element in the set of matched elements, including text and comment nodes.

You need to filter by nodeType:

$('.news article p').each(function() {
    $('.news article p').contents().each(function(idx, ele) {
        if (ele.nodeType == Node.TEXT_NODE) { // if text node.....
            var newele = ele.textContent.replace('Express Entry',
                    '<a href="https://www.ackahlaw.com/resources/check-your-express-entry-score">Express Entry</a>');
            $(ele).replaceWith(newele)
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div class="news">
    <article>
        <p>text1 <a href="link">Express Entry</a> text2 Express Entry text3</p>
        <p>text4 <a href="link">Express Entry</a> text5 Express Entry text5</p>
    </article>
</div>

Upvotes: 2

Related Questions