简体   繁体   中英

best way to target the parent div - javascript

<div id='a_div'>
    <ul>
        <li><button type='button' onclick='a_function()'>Button</button>
    </ul>
</div>

in the example set up above, what would be the best way to pass the div's id into a_function is there a better way than doing onclick='a_function(this.parentNode.parentNode.parentNode.id)'

如果您使用的是JQuery,那么.closest()可以解决您的问题。

Adding jsFiddle demos since the down vote suggests my answer is incorrect.


If you want to take it out of the inline handler, you could just pass this , then traverse in the method...

onclick='a_function(this)'

function a_function(el) {
    var id = el.parentNode.parentNode.parentNode.id
}

DEMO: http://jsfiddle.net/CUyZ4/


Or if you don't like to repeat parentNode , make a function...

function up(el, n) {
    while(n-- && (el = el.parentNode)) ;
    return el;
}
function a_function(el) {
    var id = up(el, 3).id;
}

DEMO: http://jsfiddle.net/CUyZ4/1/


Or use it directly inline...

onclick='a_function(up(this, 3).id)'

DEMO: http://jsfiddle.net/CUyZ4/2/

The best way now that the OP says jQuery is acceptable, is to use the parents function

function a_function(){
    var self = $(this), 
        parentDiv = self.parents('div');
}

This will get you the first div it encounters while traversing up the DOM chain. Ofcourse, if you want it to be a bit more specific, you can specify a particular class for all those divs and then target them as self.parents('div.someClass')

Fiddle added

Click to check working fiddle

You can use simple "upTo" function to get the first ancestor with a particular tagName . If no suitable element is found, it returns undefined :

function upTo(el, tagName) {
  tagName = tagName.toLowerCase();
  var el;
  do {
    el = el.parentNode;
    if (el.tagName.toLowerCase() == tagName) {
      return el;
    }
  } while (el.parentNode)
}

But if you're using jQuery, no doubt you'd prefer that.

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