Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Whats wrong with my code...(querySelector)

<h1 id="h1">Welcome to my page</h1>
<p>Hello my name is Tani, welcome to my page.</p>
<ul class="list reset">
 <li><a href="" title="1">1</a></li>
 <li><a href="" title="2">2</a></li>
 <li><a href="" title="3">3</a></li>
 <li><a href="" title="4">4</a></li>
 <li><a href="" title="5">5</a></li>
</ul>
<input type="text">
<button class="btn">start</button>

var btn = document.querySelector(".btn");
btn.addEventListener("click",() => {
    document.getElementById("h1").style.color = "red";
    document.getElementById("h1").style.color = document.querySelector("input").value;
    document.querySelector("[title=1]").style.backgroundColor = "pink";
    document.querySelectorAll(".list li:nth-child(even)").style.backgroundColor = "red";
});

I have been checked many times but querySelector won't change the background Color...

2 Answers

Ryan Beckett
Ryan Beckett
14,921 Points

You're missing the anchor tag and the quote marks.

document.querySelector("a[title='1']").style.backgroundColor = "pink";
Steven Parker
Steven Parker
220,477 Points

Even if your target is a single element, the "querySelectorAll" function returns a collection which does not have a "style" property. You can add an index to select a specific element from the collection, but if you want the first one you can simplify the code by using "querySelector" instead, which does return a single element.