Picking up parent div attributes through child elements

Asked

Viewed 23,399 times

9

I own several structures that follow a unique style:

<div data-id="1">
 <div>
   <button>Descobrir é o data-id desta estrutura</button> 
 </div>
</div>

with jQuery or Javascript as I could get the data-id (1) of the div through the click in the button?

  • 1

    $('button').parent().parent().data('id');

2 answers

15


I suggest you use the .closest() thus:

$('button').on('click', function () {
    var target = $(this).closest('[data-id]');
    alert(target.data('id'));
});

jsFiddle: http://jsfiddle.net/5t59xu5f/

The .closest() climbs into the DOM for the first element the selector indicates/searches. The selector '[data-id]' means "an element with the attribute data-id, regardless of its value, provided it has the attribute".

That way you avoid type code .parent().parent() which is difficult to maintain and to know to which element it applies.

  • 1

    Good, not to mention that in a future HTML maintenance and possible insertion of a new DIV level, you will not need to maintain the JS also by adding a new .Parent().

  • 1

    I gave my positive and correct marking for this fact of not needing a maintenance together if necessary, I found it cleaner to work, out that I did not know this function, +1 for my learning, thanks!!!

  • like this .closest() behaves within the onclick="fun(event)"? function fun(e) {&#xA; e.preventDefault();&#xA; console.log(e.closest('[data-id]')); Says that the Closest is a function.

  • @Thomsontorvalds if you’re using the e you must do e.target.closest(...etc in native JS or $(e.target).closest( with jQuery

4

You can do it this way using parent() and then data():

$('button').on('click', function(){
    alert($(this).parent().parent().data('id'));
});
  • And if there are several div’s inside each other, I have to use the parent() as many times as I have a div?

  • 1

    Yes, parent() is related to the level, for each div must have a parent().

  • 2

    I suggest reading: http://jquerybrasil.org/uso-dos-methodos-parents-ou-closest/

  • @Luishenrique good reference, really the use of closest makes it much easier.

Browser other questions tagged

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