1

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!

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.