mrkkr91 mrkkr91 - 3 months ago 8
CSS Question

How to toggle single element with this same class like another

I have HTML code something like this:

<img src="img.png" class="arrow"><h2 class="title">Heading 1</h2>
<p class="intro">Lorem Ipsum 1</p>

<img src="img.png" class="arrow"><h2 class="title">Heading 2</h2>
<p class="intro">Lorem Ipsum 2</p>

<img src="img.png" class="arrow"><h2 class="title">Heading 3</h2>
<p class="intro">Lorem Ipsum 3</p>


If I click first img element I would like to toggle "intro" class, but only the first element. If I click secont img, toggle second "intro", etc. How I can do this in jQuery? ("intro" has display:none; in CSS). I tried select pseudo-class:

$(".intro:first-child").click(function() {
$("intro:first-child").toggle();
}


but it doesn't work. Maybe I should use id (id="intro-1", "intro-2", etc) instead class and select in jQuery each element separately?

Answer

Use nextAll() method and :first pseudo class selector. Attach click event handler to the img tag and inside handler this refers to the clicked elements dom object.

// attach click event handler to all img tag
$(".arrow").click(function() {
    // get first `.intro` after the clicked img tag
    $(this).nextAll('.intro:first').toggle();
})

$(".arrow").click(function() {
  $(this).nextAll('.intro:first').toggle();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="img.png" class="arrow">
<h2 class="title">Heading 1</h2>
<p class="intro">Lorem Ipsum 1</p>

<img src="img.png" class="arrow">
<h2 class="title">Heading 2</h2>
<p class="intro">Lorem Ipsum 2</p>

<img src="img.png" class="arrow">
<h2 class="title">Heading 3</h2>
<p class="intro">Lorem Ipsum 3</p>

Comments