简体   繁体   中英

How can i get the Id from the next element?

I'm trying to get the ID from the next element, but i get this - "undefined"...

What am i doing wrong?

http://jsfiddle.net/84x9v/

HTML:

<a class="col" onclick="getId()">
    <div id="1"><span>1</span></div>
</a>

JavaScript:

function getId(){
  var get = $(this).next("div").attr("id");
  alert(get);
}

remove the inline js

<a class="col">
    <div id="1"><span>1</span></div>
</a>

and use an event handler

$('.col').on('click', function() {
    var get = $(this).find("div").prop("id");
    alert(get);
});

note that putting a block element inside an anchor generally isn't very good practice, and the div is a child of the anchor, it's not the next sibling.

'cause it's not the 'next' element.

function getId(){
  var get=$(this).find("div").attr("id");
  alert(get);
)

should work...

You're using jQuery and .next() wrong. Remove the inline event handler, use .find() instead of .next() , and try:

function getId() {
    var get = $(this).find("div").attr("id");
    alert(get);
}
$('a').click(getId)

jsFiddle example

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