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
jordansangalang
5,042 PointsHow to select specific elements in Javascript?
When learning CSS one of the first things you learn is how to Select the exact element you want to style. For example:
.class-name h1 { color: green; }
You can even select multiple elements at once using commas:
.class-name h1, .class-name h2 { color: red }
These instructions were pretty straight forward and explicitly taught. Why am I finding it so hard to find resources that spell this process out in JavaScript? I'll see people in tutorials using a sort of 'Dot-Notation' to select things. Do you know of any good concrete resources that teach this? I've tried googling articles and videos, but I haven't found anything for absolute beginners.
3 Answers
<noob />
17,063 PointsIn javascript u can select specific elements on the page with the DOM. Imagine i have an index.html file which has a <p> tag with the id="p-tag". If i want to change the COLOR of the p tag in javascript ill do it like that:
//first i get a reference to the pTag element on the page with the id "p-tag"
const pTag = document.getElementsById("p-tag");
//change the color of the p tag to red.
pTag.style.color= "red";
Sam Glister
1,704 PointsHello,
One of the simplest methods for selecting an element in Javascript is using the getElementById method.
Here is some useful documentation on it :)
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
I hope this helps
Cody Packer
16,836 PointsThe querySelector and querySelectorAll methods are versatile and commonly used. Here are the MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector