1

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.

Sam
  • 608
  • 4
  • 11
HPWD
  • 2,232
  • 4
  • 31
  • 61
  • Ask yourself .. `find()` what? https://api.jquery.com/find/ – charlietfl Sep 03 '18 at 23:06
  • I was so focused on the traversing that I forgot what I was looking for! :duh!: That's why it's good to another another set of eyes. – HPWD Sep 03 '18 at 23:09

1 Answers1

0

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').

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I thought attr() and data() were essentially the same thing, are they not? – HPWD Sep 03 '18 at 23:24
  • In your example, you left off `.find()` - was that a typo or intentional? – HPWD Sep 03 '18 at 23:25
  • Similar, but not the same. `data()` extracts a *data attribute* - that is, an attribute whose name starts with `data-`. But `attr` extracts *a generic attribute*. For example, you could have done `.attr('data-id')`, but `data('id')` is more appropriate. – CertainPerformance Sep 03 '18 at 23:25
  • 1
    I didn't use `.find` because there was no need to use it - press "Run code snippet". No need to find an element when you already know exactly where it is – CertainPerformance Sep 03 '18 at 23:26
  • Regarding `data` and `attr`, I understand what you are saying but I'll need to dig deeper into that. At least now I know I need to look into this deeper so right there is a lesson learned today! :D – HPWD Sep 03 '18 at 23:27
  • Regarding my comment about the `find()`, I had a brainfart. I knew that. :rolleyes: – HPWD Sep 03 '18 at 23:28