I have a JavaScript file that prints the title attribute of the child img element inside of it.
In other words, I have an img tag inside an a tag. The img tag has a title attribute inside of it. I want to get that attribute.
Here is my JavaScript code. The el variable is the a element which contains the img element.
c.innerHTML += x + y + "<h1>" + el.childNodes[0].title +"</h1>" + z;
For some reason, however, the el.childNodes[0].title doesn’t work. It just returns the following value:
undefined
I’ve tried using el.firstChild.title as well, but it still returns the same value.
Here is my HTML code:
<a class="nanobox-img" href="index.html" rel="nanobox-single-override">
<img src="../../images/testnull.gif" title="This is a NanoBox Demo"/>
</a>
Instead of
childNodes, usechildren.This is because most browsers will consider white space between nodes (line breaks, tabs, etc.) to be a DOM text node, so the first node is likely the that text node.
You could also do this…
…though I think
.childrenhas a little broader support.