Reputation: 9043
How can I retrieve this Id using jQuery?
<span data-itemkey="40e1eec6-f949-468e-8a25-ba97d0ec3fb2" class="word">
<div class="additionalStyling green" id="2">Approval Process</div>
</span>
I tried this which returns undefined
$(document).on("click", ".word", function (e) {
var id = $(".word:first-child").attr("id");
}
Upvotes: 2
Views: 69
Reputation: 32354
Try:
$(document).on("click", ".word", function (e) {
var id = $(this).find('[id]').attr('id');
});
Upvotes: 0
Reputation: 29624
children accepts a selector so you can make the above shorter thus:
$(document).on("click", ".word", function (e) {
var id = $(this).children(':first').attr('id');
}
Upvotes: 0
Reputation: 167162
Change this:
var id = $(".word:first-child").attr("id");
To:
var id = $(this).find("> div").first().attr("id");
Just to make sure, I am not copying the same one:
var id = $(this).children().first().attr('id');
Upvotes: 3
Reputation: 87203
As there will be multiple elements with class .word
, $('.word')
will return a set of elements.
Use
$(this) // The element that is clicked
.children() // Get all direct descendants
.first() // Get first element from it
.attr('id'); // Get the `id` attribute value
Upvotes: 2