Best way to set up parent div - javascript

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

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

+4
source share
4 answers

If you are using jQuery then .closest() may solve your problem.

+3
source

Adding jsFiddle demos since voting down says my answer is incorrect.


If you want to pull it out of the built-in handler, you can just go through this and then go through 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 repeating parentNode , create 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 right on the line ...

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

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

0
source

The best way when the OP says jQuery is acceptable is to use the parents function

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

This will give you the first div that he will meet after going through the DOM chain. Of course, if you want it to be more specific, you can specify a specific class for all these divs and then direct them as self.parents('div.someClass')

Added script

Click to check working script

0
source

You can use the simple upTo function to get the first ancestor with a specific tagName . If no matching 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 use jQuery, you will probably prefer this.

0
source

Source: https://habr.com/ru/post/1402796/


All Articles