Select the first element after another element:
let formAfterDivider = document.querySelector("hr + form"); console.log(formAfterDivider);
Try it out for yourself by going to the testing page and running the code in the browser console.
Tip: Press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, Chrome OS) to open the chrome console.
Let’s take a look at an example:
<p></p> <div></div> <p></p> <p></p>
This example has a div and three paragraph elements. We want to select a paragraph that is placed after a div element.
let firstParagraphAfterDiv = document.querySelector("div + p");
This line of code does exactly that. In this selector, we input a div tag followed by a plus symbol. This tells the method we to select an element after the div element.
Finally, we tell the method that we want to select a paragraph after the div element. We can do that with a p tag.
Note that this method selects siblings that are on the same level. Parent and child elements will be ignored.
document.querySelector("referenceElement + selectedElement");