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

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 the only variable statusis printed to the console, and the Variables idand detailsprint as "undefined". But if I changed the meta tags to:

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

Then only the variable will be printed to the console id.

What am I missing?

+4
source share
2 answers

$('meta')returns a jQuery array object containing all three elements meta.
$('meta').data('status')returns the value of the attribute data-statusof the first element , and it works correctly.
However, $('meta').data('id')trying to read the data attribute idfor the first element, but it is not.

.

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

, (, meta )

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

- :

<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');  
+9

data() , data- * undefined.

, data- *.

var status = $('meta[data-status]').data('status'),
  id = $('meta[data-id]').data('id'),
  details = $('meta[data-details]').data('details');
console.log(status, id, details)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<meta data-status="stopped">
<meta data-id="0001">
<meta data-details="Example details">
Hide result
+5

Source: https://habr.com/ru/post/1657952/


All Articles