Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: why can I only get the first data attribute?

Tags:

jquery

I have the following jQuery:

var status = $('meta').data('status'), 
    id = $('meta').data('id'), 
    details = $('meta').data('details');           
    console.log(status, id, details);

and the following HTML,

<head>
    <meta data-status="stopped" > 
    <meta data-id="0001" >
    <meta data-details="Example details" >

and only the status variable is printed to console and the id and details variables are printed as 'undefined'. But if I rearrange the meta tags to:

<head>
        <meta data-id="0001" >
        <meta data-status="stopped" > 
        <meta data-details="Example details" >

Then only the id variable will print to console.

What am I missing?

like image 420
rlsaj Avatar asked Dec 07 '22 20:12

rlsaj


1 Answers

$('meta') returns jQuery array-like object containing all three meta elements.
$('meta').data('status') returns data-status attribute value of the first element, and it works properly.
However, $('meta').data('id') tries to read data attribute id of the first element too, but there isn't.

You either need to combine all data attributes into a single meta.

<meta data-status="stopped" data-id="0001" data-details="Example details"/> 

This way, you can do (assuming that it is the first meta tag in your document)

var status = $('meta').data('status'), 
    id = $('meta').data('id'), 
    details = $('meta').data('details');   

Another way is to use attributes in selectors:

<meta data-status="stopped" > 
<meta data-id="0001" >
<meta data-details="Example details" >

var status = $('meta[data-status]').data('status'), 
    id = $('meta[data-id]').data('id'), 
    details = $('meta[data-details]').data('details');  
like image 93
Yeldar Kurmangaliyev Avatar answered Jan 06 '23 07:01

Yeldar Kurmangaliyev