Reputation: 320
I'm trying to turn an image source into a string so I can run substring()
on it. I used the following JavaScript to get the source:
function ShowQuizAnswers(quiz) {
var QuizImage = document.getElementById(quiz);
var ImageType = QuizImage.attributes.src;
console.log(ImageType);
}
Of course, as I soon found out, this returned an object instead of a string. I tried running .toString()
on the ImageType
variable, but that didn't work. Is there something I'm missing?
Upvotes: 5
Views: 590
Reputation: 115212
Use Element#getAttribute or directly get src
property from dom object.
function ShowQuizAnswers(quiz) {
var QuizImage = document.getElementById(quiz);
var ImageType = QuizImage.src;
console.log(ImageType);
}
or
function ShowQuizAnswers(quiz) {
var QuizImage = document.getElementById(quiz);
var ImageType = QuizImage.getAttribute('src');
console.log(ImageType);
}
FYI : The attributes
is an array like structure(NamedNodeMap). It actually helps to iterate over all attributes an element, but you can't access the attribute directly from it.
From the MDN docs:
The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. It is a NamedNodeMap, not an Array, so it has no Array methods and the Attr nodes' indexes may differ among browsers. To be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute.
Upvotes: 2