简体   繁体   中英

Get ID of next DOM element

单击类后如何获取元素的ID?

Try this:

$(".className").click(function() {
    $(this).next().attr("id");
});
  1. $(".className") : select elements with class className
  2. .click() : jQuery onclick handler
  3. $(this) : selects element again
  4. .next() : get next element
  5. .attr("id") : retrieve id attribute

If you want to get it on click, add a click() handler

You could use jQuery next function to select the "immediately following sibling":

$(function() {
    $(".yourClassName").click(function() {
        let yourNextElementId = $(this).next().attr("id");
    });
});

Use next() to get the next element and use attr() to get its ID":

 $(document).ready(function() { $('.sample_class').click(function() { alert($(this).next().attr('id')) }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="sample_class">element with class</div> <div id="sample_id">next element with id</div>

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