Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
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 Parker217,443 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.