简体   繁体   中英

jQuery parents selector - traversing

I have an array that inserts articles. When I click the h3 (which has the title) I want to display more information based on the article's index. I think I need to go up to the <section id="main"> to find the index of the <article> I clicked on starting from my <h3> .

Here's my HTML:

    <section id="main" class="container">
      <article class="article">
        <section class="featuredImage">
          <img src="images/article_placeholder_1.jpg" alt="" />
        </section>
        <section class="articleContent">
            <a href="#"><h3>Test article title</h3></a>
            <h6>Lifestyle</h6>
        </section>
        <section class="impressions">
          526
        </section>
        <div class="clearfix"></div>
      </article>
    </section>

Here is my attempt of getting the index:

$('.articleContent a').on('click', function(e) {
    var $target,
        $parent,
        $index;
    e.preventDefault();

    $target = $(e.target);
    $parent = $target.parents('.main');
    $index = $parent.find('.article').index();
    console.log($index);
});

Your HTML nesting structure is the following

section#main > article.article > section.articleContent > a

You have to search ascendants for more than one level up, so parent() is not enough.

parents() on the other side can travel for more than one parent and by passing a selector, you can filter the parents.

$('.articleContent a').on('click', function(e) {
    e.preventDefault();
    var index = $(this).parents('.article').first().index();
    console.log(index);
});

So this will find the first element with the class "article". Notice you could also be more specific, by using the selector "article.article"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM