Question

My code doesn't seem to be working. I am trying to access the first child of the div and set an attribute, but the console gives me this error:

TypeError: Object # has no method 'setAttribute'

My Code:

<div>
    <p id="one"><span id="uno">1</span></p>
    <p id="two"><span id="dos">2</span></p>
    <p id="three"><span id="tres">3</span></p>  
</div>
<script>
var divvy = document.getElementsByTagName("div").item(0)
divvy.firstChild.setAttribute("style", "color: violet;");
</script>
Was it helpful?

Solution

Use the .children collection to avoid the text node.

divvy.children[0].setAttribute("style", "color: violet;");

In modern browsers (like IE9+), you can use .firstElementChild instead of .firstChild.

divvy.firstElementChild.setAttribute("style", "color: violet;");

And off topic, but I wouldn't use setAttribute to set the color. I'd use the .style property.

divvy.firstElementChild.style.color = "violet";

OTHER TIPS

The first child of the DIV is a text node containing the empty space before the P elements. Instead, try this:

var divvy = document.getElementsByTagName("div").item(0)
divvy.getElementsByTagName('p')[0].setAttribute("style", "color: violet;");

This explicitly selects the first P element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top