Return parent tag ID when clicking a button

1

I have a set of buttons where I want to return the ID of the parent tag when a button is clicked to implement a function.

<div id="botoes">
  <button data-for="cod" onclick="checkbox(this)">cod</button>
  <button data-for="nome" onclick="checkbox(this)">nome</button>
  <button data-for="barras" onclick="checkbox(this)">barras</button>
  <button data-for="desc" onclick="checkbox(this)">desc.</button>
</div>

How do I do this? My "google-fu" did not help me ...

    
asked by anonymous 10.09.2014 / 19:03

2 answers

3

Use parentElement to get the DOM element relative to the parent. parentNode is only for compatibility with very old browsers, but can be removed.

function checkbox(child) {
    var parent = child.parentElement || child.parentNode;
    var id = parent.getAttribute('id');
}

More details: parentElement and parentNode

    
10.09.2014 / 19:17
1

I know that for some time the question has been posted, however, it remains as a way of learning for the others that pass here: -)

In this case, you could use a jQuery feature: .parent() .

It, as well as .closest() , is useful for the question, however, since you want to simply get the parent element without any specification (via id or class), I suggest .parent() .

It would look like this ( demo ):

function checkbox(btn){
  var idParent = $(btn).parent().attr('id'); 
  alert(idParent);
}

Or if you prefer a pure javascript ( demo ):

function checkbox(btn) {
    var idParent = btn.parentElement.id || btn.parentNode.id;
    alert(idParent);
}

That's the tip.

    
16.02.2015 / 04:16