Let's say I have many of these in my content div
: <cite class="fn">blabla</cite>
How can I check every cite
tag's content (in this case: blabla
) with class fn
to see if it equals to "sometext" then change it's color to red ?
Very simple.
Let's say I have many of these in my content div
: <cite class="fn">blabla</cite>
How can I check every cite
tag's content (in this case: blabla
) with class fn
to see if it equals to "sometext" then change it's color to red ?
Very simple.
$('cite.fn:contains(blabla)').css('color', 'red');
Edit: though that will match "blablablabla" as well.
$('cite.fn').each(function () {
if ($(this).text() == 'blabla') {
$(this).css('color', 'red');
}
});
That should be more accurate.
Edit: Actually, I think bazmegakapa's solution is more elegant:
$('cite.fn').filter(function () {
return $(this).text() == 'blabla';
}).css('color', 'red');;
You can make use of the amazing .filter()
method. It can take a function as its parameter, which will reduce the jQuery collection's elements to those that pass its test (for which the function returns true). After that you can easily run commands on the remaining elements:
var searchText = 'blabla';
$('cite.fn').filter(function () {
return $(this).text() === searchText;
}).css('color', 'red');
$("cite.fn:contains('"+searchText+"')").filter(function(){return $(this).text().length==searchText.length});
–
Armourer :contains()
is not a standard selector, so jQuery has to use its own engine, not the faster native one (which it normally uses). So what you win on the one side, you lose on the other. You could do a jsPerf benchmark and post the result here. –
Portend querySelectorAll()
supports the selector, it is much quicker. –
Portend You could potentially do something like:
$('cite.fn').each(function() {
var el = $(this);
if (el.text() === 'sometext') {
el.css({ 'color' : 'red' });
}
});
This fires a function against each cite
that has the class fn
. That function checks if the current cite
's value is equal to 'sometext'.
If it is, then we change the CSS color
(text-color) property to red
.
Note I'm using jQuery in this example, as you've specifically tagged your question jQuery
. Ignore the downvote, this was applied before I edited a typo that I'd made (el.val()
rather than el.text()
)
Without jQuery:
var elms = document.querySelectorAll("cite.fn"), l = elms.length, i;
for( i=0; i<l; i++) {
if( (elms[i].innerText || elms[i].textContent) == "blabla") {
elms[i].style.color = "red";
}
}
© 2022 - 2024 — McMap. All rights reserved.
<cite class="fn">textblabla</cite>
, which may cause problems if the search term could easily be a substring. – Bony