Categories
JavaScript Selecting

JavaScript for optimizers #28: How to select the first element after another element?

Example

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.

We select a form element after an hr element
We select a form element after an hr element

Breakdown

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.

Syntax

document.querySelector("referenceElement + selectedElement");