JavaScript jQuery Basics Introducing jQuery jQuery vs. JavaScript

Ashley Campbell
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ashley Campbell
Front End Web Development Techdegree Graduate 19,905 Points

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
204,004 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.

Ashley Campbell
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Ashley Campbell
Front End Web Development Techdegree Graduate 19,905 Points

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
204,004 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.