Tomas Ramirez Sarduy
Tomas Ramirez Sarduy

Reputation: 17471

Find and replace a html element with an specific text

I have something like this HTML code:

<ul>
<li><a href="#">21</a></li>
<li><a href="#">10</a></li>
<li><a href="#">6</a></li>
<li><a href="#">1</a></li>
<li><a href="#">7</a></li>
<li><a href="#">5</a></li>
</ul>

And I want to make a Jquery code that add class to the link with the gave text (notice that have to be exactly the text). For example, if I call Method(1, "replaced text") then this has to be the HTML result:

<ul>
<li><a href="#">21</a></li>
<li><a href="#">10</a></li>
<li><a href="#">6</a></li>
<li><a class="myclass" href="#">1</a>replaced text</li>
<li><a href="#">7</a></li>
<li><a href="#">5</a></li>
</ul>

Upvotes: 0

Views: 233

Answers (4)

georg
georg

Reputation: 214949

jQuery doesn't provide a selector for "this exact text", but it's easy to write (laaeftr). You can also use a more flexible "matches" selector, which matches a text against a regular expression (given without delimiters):

$.extend($.expr[':'], {
    matches: function (el, index, m) {  
        var s = new RegExp(m[3]);
        return s.test($(el).text());
    }  
});

Once we've got that, the rest is easy:

$("li > a:matches(^10$)").addClass("foo")

http://jsfiddle.net/am7rY/

Upvotes: 0

redmoon7777
redmoon7777

Reputation: 4526

try:

function someName(niddle, new_text)
{
    $('ul a').each(function(){
        if($(this).text() == niddle){
            $(this).addClass('myclass');
            $(this).after(new_text);
        }
    });
}

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

You can use filter() to match the element, then chain addClass() into after():

$("li > a").filter(function() {
    return $(this).text() == "1";
}).addClass("myclass").after("replaced text");

Upvotes: 1

bjelli
bjelli

Reputation: 10070

jQuery offers a selector for that

$('a:contains(10)').addClass('myclass');

Try the code at

http://jsfiddle.net/8zmus/

Upvotes: 0

Related Questions