Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) The Browser Environment Thinking Globally

document.getElementsByTagName('p').style.background = 'yellow'

Hi,

I tried to do manipulate by TagName , as below but it didn't work document.getElementsByTagName('p').style.background = 'yellow' OR document.getElementsByTagName('p').style.backgroundColor = 'yellow'

what might be wrong? Thanks

2 Answers

Steven Parker
Steven Parker
229,744 Points

The result of getElementsByTagName is a collection, not a single element, so it would not have a "style" property.

You can index the collection to access a single element. For example, if you wanted to alter the very first paragraph (index 0) on the page:

document.getElementsByTagName('p')[0].style.backgroundColor = 'yellow';

getElementsByTagName('p') will return a collection of all paragraph tags on the page. In order to change the background color of every paragraph tag on the page, you must loop through each paragraph tag individually and set it.

for (var p in document.getElementsByTagName('p')) { 
    // Skip the collection elements that are not indexed by numbers, such as 'length'
    if (!isNaN(p) === true) {
        document.getElementsByTagName('p')[p].style.backgroundColor = 'yellow'; 
    }
}