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

Soufiane Bdaoui
Soufiane Bdaoui
9,602 Points

Can't Figure why this JS code is wrong

HTML code

!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="script.js"></script>   
</head>
<body>
    <section>
        <div><a href="FirstLink.html" class="aLink"> First Link</a</div>
        <div><a href="SecondLink.html" class="aLink">Second Link</a> </div>

    </section>


</body>
</html>

JS code

var linkPages = document.getElementByClassName("aLink");

function changeText(){
    linkPages.style.color="yellow";
    linkPages.style.backgroundColor="yellow";

}

linkPages.onClick = changeText();
Steven Parker
Steven Parker
229,644 Points

Can you provide a link to the course page you are working with?

1 Answer

Steven Parker
Steven Parker
229,644 Points

Three things stand out even without knowing the specific objectives of this code:

I notice you have "getElementByClassName", but the actual function is "getElementsByClassName" (plural).

Also, the actual function returns an element collection, not a single element, so it would not have "style" property. But the individual elements in it would, perhaps you need a loop?

And finally, it would be most unusual to set both "color" and "backgroundColor" to the same value unless you were intending to make the text invisible.

Soufiane Bdaoui
Soufiane Bdaoui
9,602 Points

Yeah, I was expecting it to work like getElementByID(). Thanks for the help, now I get it.