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 jQuery Basics Introducing jQuery jQuery vs. JavaScript

Why Doesn't This Work?

I loaded the workspace from the video and thought i would try and select the 'box' using some DOM traversal i had previously learnt, but no success! The error i am getting is ..."Cannot read property 'style' of null". So the selector isnt't working!

const h1 = document.querySelector('h1');

const box = h1.querySelector('div');

box.style.backgroundColor = 'red';

i thought it was possible to traverse to the <div .box> starting from a previously defined element i.e the <h1>??

<body>

<div class="container">

<h1>Hello jQuery!</h1>

<div class="box"></div>

</div>

Thanks!

1 Answer

Steven Parker
Steven Parker
231,269 Points

If you start at a particular element, the selector function will only find elements that are contained inside the first element. In this case the elements are siblings so it doesn't work.

You can still select a sibling if you first traverse to the parent:

const box = h1.parentNode.querySelector('div');

You can also traverse directly to the sibling without the selector:

const box = h1.nextElementSibling;

Also note that the color change won't have any visible effect unless you give some content to the div.

Oh ok i wasn't aware of that. Thanks Steven that makes sense now!

so you always have to traverse back to the outer most parent? in the case below would i be able to traverse to the <h1> with querySelector from the '.test' div? or would i have to go back further to the '.container' div in order to select the <h1>?

<div class="container">

<div class = "test">

     <h1>Hello jQuery!</h1>

     <div class="box"></div>

</div>

</div>

thanks!

Steven Parker
Steven Parker
231,269 Points

You only need to be at the nearest common parent. So from the "test" div you could select the h1 or the "box" div.

awesome thanks for help you legend!