How to get the data from meta tags in JavaScript

3 Answers

0 votes
<meta name="title" content="title - text" />
<meta name="description" content="description - text" />
const title = document.querySelector('[name=title]');
const description = document.querySelector('[name=description]');

console.log(title.content); 
console.log(description.content); 


  
    
    
/*
run:
    
"title - text"
"description - text"
    
*/

 



answered Jun 15, 2021 by avibootz
0 votes
<meta name="title" content="title - text" />
<meta name="description" content="description - text" />
function getMetaData(metaName) {
  const metanames = document.getElementsByTagName('meta');

  for (let i = 0; i < metanames.length; i++) {
    if (metanames[i].getAttribute('name') === metaName) {
      return metanames[i].getAttribute('content');
    }
  }
  return '';
}

console.log(getMetaData('title'));
console.log(getMetaData('description'));


  
    
    
/*
run:
    
"title - text"
"description - text"
    
*/

 



answered Jun 15, 2021 by avibootz
0 votes
function getMetaData(attr,val) {
  	return document.querySelector(`[${attr}=${val}]`).content;
}


console.log(getMetaData('name','title')); 
console.log(getMetaData('name','description')); 



  
    
    
/*
run:
    
"title - text"
"description - text"
    
*/

 



answered Jun 15, 2021 by avibootz

Related questions

3 answers 287 views
287 views asked Apr 19, 2014 by avibootz
1 answer 180 views
180 views asked Jun 28, 2016 by avibootz
1 answer 258 views
1 answer 110 views
...