Reputation: 238617
I'm trying to learn how to use native JavaScript without relying on jQuery. I would like to get the value of a specific attribute on an element. How can I do this without using jQuery? If there are inconsistencies between browsers, please mention them.
myImage = document.getElementById("logo");
console.log('myImage src attribute value');
console.log('myImage data-foo attribute value');
<img id="logo" src="logo.png" data-foo="bar">
Upvotes: 0
Views: 274
Reputation: 66093
Use .getAttribute()
to assess the value.
myImage = document.getElementById("logo");
console.log(myImage.getAttribute('src'));
console.log(myImage.getAttribute('data-foo'));
<img id="logo" src="http://placehold.it/500x500" data-foo="bar">
For the HTML5 data-
attributes, you can still access with the conventional method, or even use .dataset
(but only with HTML5-compliant browsers), i.e: .dataset.foo
:
myImage = document.getElementById("logo");
console.log(myImage.getAttribute('src'));
console.log(myImage.dataset.foo);
<img id="logo" src="http://placehold.it/500x500" data-foo="bar">
Upvotes: 1
Reputation: 27450
Check W3C DOM specification: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html, in particular Element.getAttribute().
Upvotes: 0