L8R
L8R

Reputation: 431

How to retrieve meta tag data?

What I am trying to do is get a certain meta tag.

Looking for something similar to this:

<meta name="age" data-userid="number">

var meta = document.getElementsByTagName('meta');
var id = meta.substring(34, 37);
console.log(id);

I am trying to get the data-userid value. The other questions do not help because they are only asking how to get the content of the meta.

My code from one of the answers (still doesn't work):

var idl = localStorage.getItem("id");
if (typeof idl !== 'undefined' && idl !== null){}else if (typeof idl == 'undefined' || idl == null){
    localStorage.removeItem("id");

    var meta = document.getElementsByTagName('meta')[0];
    var idget = meta.getAttribute("data-userid");
    var id = idget;
    localStorage.setItem("id", id);
}

Upvotes: 1

Views: 2118

Answers (3)

Sarun UK
Sarun UK

Reputation: 6746

//Using JS
var meta = document.getElementsByTagName('meta')[0];
console.log(meta.getAttribute("data-isunder13"));

//Using JQuery
var data = $('meta[name=age]').attr('data-isunder13');
console.log(data);

//Using JS
var meta = document.getElementsByTagName('meta')[0];
console.log(meta.getAttribute("data-isunder13"));

//Using JQuery
var data = $('meta[name=age]').attr('data-isunder13');
console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta name="age" data-isunder13="false">

Upvotes: 1

Shub
Shub

Reputation: 2704

There can be multiple meta tags in a page, you should add another parameters such as name in this case to uniquely identify element you are looking for,

You can use dataset to get a data value:

const value=document.querySelector('meta[name="age"]').dataset.isunder13;
console.log(value);
<meta name="age" data-isunder13="false">

Upvotes: 1

Harshana
Harshana

Reputation: 5476

You can use getAttribute() method in the specific element to retrieve values.

var meta = document.getElementsByTagName('meta');
console.log(meta[0].getAttribute("data-isunder13"));
<meta name="age" data-isunder13="some value">

Upvotes: 1

Related Questions