Return parent tag ID when clicking a button

Asked

Viewed 1,558 times

2

I have a set of buttons where I want to return the parent tag ID 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 it? My "google-fu" didn’t help me...

  • 1

    You want to have access to the "buttons" id from within the function checkbox, that’s it?

  • no, the checkbox function is just her name.. she does something else and you didn’t even have to be there.

  • Wow, so I don’t understand why you accepted the answer below...

2 answers

4


Use the parentElement to obtain the element DOM relative to the father. The 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

  • thanks for the information... I ended up reformulating the logic of the system to become more plausible...

1

I know it has been some time since the question was posted, however, it is a way of learning for the others who pass by :-)

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

Him, as well as the .closest() serve for the question, however, as you want to simply take the parent element without any specification (via id or class), I suggest the .parent().

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);
}

Tip.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.