Ashley CampbellFront 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>??
<h1>Hello jQuery!</h1> <div class="box"></div>
Steven Parker204,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.