0

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">
Andrew
  • 212,236
  • 189
  • 499
  • 691
  • 1
    possible duplicate of [Cross-browser, javascript getAttribute() method?](http://stackoverflow.com/questions/3755227/cross-browser-javascript-getattribute-method) – Marko Gresak Jan 20 '15 at 23:27

2 Answers2

1

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">
Terry
  • 57,476
  • 13
  • 82
  • 106
0

Check W3C DOM specification: http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/idl-definitions.html, in particular Element.getAttribute().

c-smile
  • 25,702
  • 7
  • 55
  • 82