edit
When the edit is clicked, I'd lik" />
edit
When the edit is clicked, I'd lik" />
edit
When the edit is clicked, I'd lik"/>

using jQuery to traverse the DOM

122 views Asked by At

Given the following html DOM:

<div>
    <div>
        <input data-id="somevalue">
    </div>
    <div>
        <a href="">edit</a>
    </div>
</div>

When the edit is clicked, I'd like to get the somevalue.

A) Would I use .parent().parent().find() or is there a more appropriate solution?
B) How would I get the value for the data-select? I know how to get it by ID or class but not clear on the syntax to use for data attributes.

Using the following:

var id = $(this).parent().parent().find().attr('id');
console.log(id);

outputs undefined so I'm not sure if I have a traversing issue or if I don't have the syntax correct for getting the data attribute value.

1

There are 1 answers

6
CertainPerformance On BEST ANSWER

You can use

$(this).parent().prev().children().data('id')

:

$('a').click(function(e) {
  e.preventDefault();
  console.log(
    $(this).parent().prev().children().data('id')
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <div>
        <input data-id="somevalue">
    </div>
    <div>
        <a href="">edit</a>
    </div>
</div>

Your .find(), with no arguments, isn't giving you any results because you didn't pass it any selector to find. Also, the attribute isn't id - the attribute is data-id, so you should use data('id') rather than attr('id').