Reputation: 17471
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
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")
Upvotes: 0
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
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
Reputation: 10070
jQuery offers a selector for that
$('a:contains(10)').addClass('myclass');
Try the code at
Upvotes: 0