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) Making Changes to the DOM Modifying Elements

Polar Digital
Polar Digital
1,141 Points

I'm trying to use document.querySelector by it doesn't seem to be working and i'm not sure what i'm doing wrong.

Struggling to use document.querySelector when it comes to the challenges.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>DOM Manipulation</title>
    </head>
    <link rel="stylesheet" href="style.css" />
    <body>
        <div id="content">
            <label>Link Name:</label>
            <input type="text" id="linkName">
            <a id="link" href="https://teamtreehouse.com"></a>
        </div>
        <script src="app.js"></script>
    </body>
</html>
app.js
let linkName = document.querySelector ("linkName");

1 Answer

Tijo Thomas
Tijo Thomas
9,737 Points

Hi, the better option here is to use toe getElementById() method. The reason for this is that specific id's should be used only once in the html. So with that said this is what the code should look like for the first challenge:

let linkName = document.getElementById("linkName").value;

You have to use the .value method to return the value of the value attribute of a text field. You could do this with .querySelector() like this:

// when using query selector to select an id you have to use the "#"
// and to select a class you have to use "."
let linkName = document.querySelector("#linkName").value;

Also remember you shouldn't have a space between querySelector and the parenthesis as you have in your code. Again, querySelector() is used to find the first instance of the desired element.

Steven Parker
Steven Parker
231,269 Points

:point_right: I'm not sure your method is "better" than Polar's.

Both methods return the same result, and take up the same space in the code. I would consider them equivalent.