Reputation: 13
I'm currently trying to implement a refreshing post feed, and have something like the following going on, trying to grab data-pid out of a child element:
HTML:
<div id="postFeed">
<div data-pid="6">
...
</div>
...
</div>
jQuery:
$(document).ready(() => {
alert($("#postFeed:first-child").attr("data-pid"));
...
});
I've tried several different methods, but all I ever get back is 'undefined'. What's the correct way to do this?
Upvotes: 1
Views: 935
Reputation: 73896
Please understand that the :first-child
selector selects all elements that are the first child of their parent. But here #postFeed
is not the child you want to target, you want to target the div
inside it. So, you just need to use :first-child
selector on that child element.
Also, instead of using .attr("data-pid")
you can simply use .data()
method. The .data()
method allows us to read data previously associated with DOM elements. Also, we can retrieve several distinct values for a single element one at a time, or as a set like:
$(document).ready(() => {
console.log( $("#postFeed div:first-child").data("pid") );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="postFeed">
<div data-pid="6">
A
</div>
<div data-pid="8">
B
</div>
</div>
Upvotes: 1
Reputation: 56
In your code it $("#postFeed:first-child") means first child of div with id postFeed.
$("#postFeed:first-child").attr("data-pid")
Instead find inside postfeed div and this can be done by using following code.
$(document).ready(() => {
alert($("#postFeed div:first-child").attr("data-pid"));
})
Upvotes: 1
Reputation: 467
There is a logic issue with the current script.
What you should be using is -
$(document).ready(() => {
alert($("#postFeed").children(":first").attr("data-pid"));
});
Upvotes: 0