Tim
Tim

Reputation: 33

Check mutiple div if contains specific text to add css class

I got a page and want to add a css class to every heading, which contains a specific word above it, inside the div "metadata". Here is an example:

<ul class="postlist">
<li><div class="postBox">
<h2><a href="http://sample.com"> Test Sample 1</a></h2>
<div class="metadata"><a href="LinkToCat" class="link" id="cat">Internal, Test</div>
</div></li>

<li><div class="postBox">
<h2><a href="http://sample.com"> Test Sample 2</a></h2>
<div class="metadata"><a href="LinkToCat" class="link" id="cat">Test</div>
</div></li>
</ul>

I tried with jquery like this:

if ($('div.postBox > div.metadata > a:contains("Internal")').length > 0)
    $( "h2 a" ).addClass( "a-internal" );

This works - But the problem is, every heading element gets the class "a-internal", because the headings don't have unique IDs/names, right? Does somebody have an idea how I can nevertheless only add the class to the specific heading?

Thanks a lot!

Upvotes: 1

Views: 649

Answers (1)

Satpal
Satpal

Reputation: 133403

Instead of if use DOM relationship to target the element. Use .closest() to traverse up-to common ancestor then use .find() to target the element.

Use

$('div.postBox > div.metadata > a:contains("Internal")')
    .closest('div.postBox') //Traverse up-to common ancestor
    .find("h2 a") //target element
    .addClass("a-internal")

$('div.postBox > div.metadata > a:contains("Internal")').closest('div.postBox').find("h2 a").addClass("a-internal")
.a-internal {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="postlist">
  <li>
    <div class="postBox">
      <h2><a href="http://sample.com"> Test Sample 1</a></h2>
      <div class="metadata"><a href="LinkToCat" class="link" id="cat">Internal, Test</div>
</div></li>

<li><div class="postBox">
<h2><a href="http://sample.com"> Test Sample 2</a></h2>
        <div class="metadata"><a href="LinkToCat" class="link" id="cat">Test</div>
</div></li>
</ul>


:has() can also be used

$('div.postBox:has(> div.metadata > a:contains("Internal"))')
    .find("h2 a") 
    .addClass("a-internal")

$('div.postBox:has(> div.metadata > a:contains("Internal"))')
    .find("h2 a") 
    .addClass("a-internal")
.a-internal {
  color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="postlist">
  <li>
    <div class="postBox">
      <h2><a href="http://sample.com"> Test Sample 1</a></h2>
      <div class="metadata"><a href="LinkToCat" class="link" id="cat">Internal, Test</div>
</div></li>

<li><div class="postBox">
<h2><a href="http://sample.com"> Test Sample 2</a></h2>
        <div class="metadata"><a href="LinkToCat" class="link" id="cat">Test</div>
</div></li>
</ul>

Upvotes: 5

Related Questions