I am trying to select a div class having specific text.
Example: <div class="foo">Foo39</div>
So, If foo class contain "foo39" text then it should be red and if it contain other text then it should be green!
I tried using CSS but no luck!
I am trying to select a div class having specific text.
Example: <div class="foo">Foo39</div>
So, If foo class contain "foo39" text then it should be red and if it contain other text then it should be green!
I tried using CSS but no luck!
JQuery provides the :contains
selector, used like so:
$('.foo:contains(Foo39)').css('background-color', 'red');
$('.foo:not(:contains(Foo39))').css('background-color', 'green');
And with pure javascript since you didnt mention you were using jQuery.... but workes with native querySelctor/All
Using querySelctorAll likely more performant than jquery's .contains
<div class="foo">Foo37</div>
<div class="foo">Foo38</div>
<div class="foo">Foo39</div>
<div class="foo">Foo40</div>
<script>
var find = "Foo40";
var needle;
var haystack = document.querySelectorAll(".foo");
var i;
for (i = 0; i < haystack.length; i++) {
if(haystack[i].innerHTML == find){
console.log("found");
haystack[i].style.background = "red";
}else{
haystack[i].style.background = "green";
}
}
</script>
Using getElementsByClassName likely more performant than querySelectorAll
<div class="foo">Foo37</div>
<div class="foo">Foo38</div>
<div class="foo">Foo39</div>
<div class="foo">Foo40</div>
<script>
var find = "Foo40";
var needle;
var haystack = document.getElementsByClassName("foo");
var i;
for (i = 0; i < haystack.length; i++) {
if(haystack[i].innerHTML == find){
console.log("found");
haystack[i].style.background = "red";
}else{
haystack[i].style.background = "green";
}
}
</script>