1

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">

1

1 Answer 1

2

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">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.