Reputation: 2737
given the following html:
<input name="name goes here" type="text" value="value goes here">
<span class="suggestInput" data-type="tag">
<img src="../images/icons/wand.png" title="Suggest an input" alt="">
</span>
im trying to find the name attribute value of the closest input, the one above the class 'suggestInput' above. In my example, it should return name goes here
I've tried:
$(".suggestInput").click(function(event) {
event.preventDefault();
var test1 = $(this).closest("input").attr("name");
var test2 = console.log($(this).find().closest("input").attr("name"));
});
and they both return 'undefined' ..
What's wrong?
Upvotes: 0
Views: 1422
Reputation: 38102
You can use .prev()
here because input
is the immediate previous sibling of your span:
var test1 = $(this).prev().attr("name");
.closest()
is not working because this method will traverse up the DOM tree and get closest matching ancestor which is not applicable in your case:
Upvotes: 1
Reputation: 388316
.closest() is used to find an ancestor element, in your case the input element is not a ancestor element of the span.suggestInput
element, it is the previous sibling so use .prev() to find it
var test1 = $(this).prev("input").attr("name");
Upvotes: 5