Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select div class containing specific text [duplicate]

Tags:

html

jquery

css

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!

like image 221
Yuan Arkiden Avatar asked Dec 01 '25 00:12

Yuan Arkiden


2 Answers

JQuery provides the :contains selector, used like so:

$('.foo:contains(Foo39)').css('background-color', 'red');
$('.foo:not(:contains(Foo39))').css('background-color', 'green');
like image 91
Kwarrtz Avatar answered Dec 03 '25 17:12

Kwarrtz


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>

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!