Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do `$('meta[name="csrf-token"]').attr('content')` in vanilla Javascript?

Tags:

javascript

I don't have jQuery and I want to know how can I do the same thing with vanilla javascript. Any help?

$('meta[name="csrf-token"]').attr('content')
like image 545
aks Avatar asked Mar 04 '17 07:03

aks


4 Answers

document.querySelector('meta[name="csrf-token"]').getAttribute('content');

That's how you do it.

like image 181
mehulmpt Avatar answered Nov 07 '22 09:11

mehulmpt


meta elements actually have a content property, so you can simply write:

document.querySelector('meta[name=csrf-token]').content

Demo:

console.log(
  document.querySelector('meta[name=csrf-token]').content
)
<meta name="csrf-token" content="example-content"/>
like image 25
gyre Avatar answered Nov 07 '22 08:11

gyre


You can also use getElementsByName

document.getElementsByName('csrf-token')[0].getAttribute('content')

like image 4
brickgale Avatar answered Nov 07 '22 08:11

brickgale


Use querySelector() method to get the element and use getAttribute() method to get the attribute value from the element.

document.querySelector('meta[name="csrf-token"]').getAttribute('content') 
like image 3
Pranav C Balan Avatar answered Nov 07 '22 08:11

Pranav C Balan