Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return an image source as a string?

Tags:

javascript

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?

like image 523
Chris Lallo Avatar asked Oct 17 '22 05:10

Chris Lallo


1 Answers

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.

like image 162
Pranav C Balan Avatar answered Oct 20 '22 16:10

Pranav C Balan