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

get element by class anme and get element by tag name is not woring

var class = document.getElementsByClassName('h1'); class.style.color = 'red'; i wnt to change class h1's color to red but its not working if i use document.getElementBytagName('h1') and change this to red it also not working

1 Answer

Steven Parker
Steven Parker
229,783 Points

Without seeing the code, this is a bit of guessing — but "h1" is most likely a tag and not a class. And "getElementBytagName" (singular and lower-case "t") is not a document method but "getElementsByTagName" {plurall and capital "T") is. And it returns an element collection so to access a single element would require using an index.

For example, if you wanted to color the first h1 element on the page red, you might do this:

headings = document.getElementsByTagName('h1');
headings[0].style.color = 'red';

For future questions always show the complete code (both HTML and JavaScript), and provide a link to the course page you are working with. A great way to share all the code at once is to make a snapshot of your workspace and post the link to it here.

hey steven why it would need index it will search for all h1 as a tag inside an html why should we need an index

and if i want to select two or more h1 elements then what to do if we select it inside a variable :

var variable = document.getElementByTagName('h1'); variable.style.color = "blue";

if i put an index beside "variable.style.color" as "variable[0 or 1].style.color" it will select only one first or second it wont put styles on both if i run these code nothing happen what to do if there will be more than 1 "h1" or any "tag" then index value wont work what to do ?

var variable = document.getElementByTagName('h1'); variable.style.color = "blue";

Steven Parker
Steven Parker
229,783 Points

You need the index to select a specific element. The entire collection has no "style" property that would allow them all to be changed at once (but you could do it with a loop).