1

I am creating an image tag using the following code..

var a = new DOMParser().parseFromString('<img src="/hello" alt="Promised">', "text/xml");
for(var b in a){
    alert('b is: ' + b + '.Value is: ' + a[b]);
}

In the above code, I am not able to get the value of alt attribute of image. Why is alt not displayed in the for loop?

I know we can get the attribute as:

var a = document.getELementsByTagName('img')[0].alt; 

But why is it not working inside of for loop?

3
  • Why are you using a loop if your code only returns a single element? Commented Dec 13, 2018 at 18:08
  • 1
    @EinarÓlafsson He's trying to loop over that element's attributes, not over a collection of elements. Commented Dec 13, 2018 at 18:10
  • 1
    I am using it to get all the attribute values of img tag..Here b is attribute name and a[b] is attribute value Commented Dec 13, 2018 at 18:10

1 Answer 1

1

It doesn't help that you are parsing it as XML, yet it isn't valid XML (no closing tag). Try this:

new XMLSerializer().serializeToString(a)

You get this parser error:

<img src="/hello" alt="Promised">
    <parsererror xmlns="http://www.w3.org/1999/xhtml" style="display: block; white-space: pre; border: 2px solid #c77; padding: 0 1em 0 1em; margin: 1em; background-color: #fdd; color: black">
        <h3>This page contains the following errors:</h3>
        <div style="font-family:monospace;font-size:12px">error on line 1 at column 34: Extra content at the end of the document
        </div>
        <h3>Below is a rendering of the page up to the first error.</h3>
    </parsererror>
</img>

If you fix the XML (closing tag) and repeat, you get:

var a = new DOMParser().parseFromString('<img src="/hello" alt="Promised"></img>', "text/xml");
new XMLSerializer().serializeToString(a)

Results in:

<img src="/hello" alt="Promised"/>

If you parse it as HTML instead:

var a = new DOMParser().parseFromString('<img src="/hello" alt="Promised">', "text/html");

You'll get this instead:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head></head>
    <body>
        <img src="/hello" alt="Promised" />
    </body>
</html>

To loop over the element's attributes, you need to fix your loop:

var elem = a.getElementsByTagName('img')[0];
for (var i = 0; i < elem.attributes.length; i++) {
    var attrib = elem.attributes[i];
    if (attrib.specified) {
        console.log('b is: ' + attrib.name + '.  Value is: ' + attrib.value);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You for your answer.. How can I get alt value inside of for loop?

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.