Discovering DOM elements positioned between two other well-established DOM elements can be achieved by utilizing a variety of methods

What is the most efficient and elegant way to select all elements between two specified elements using vanilla JavaScript? For instance, how can I target all elements between:

<h2> and <hr> .. and the result should be an [ p, p, ul ] ... but

<p>this should not be found</p>
should not be included since there is no
after it.

While I could potentially write a script to check siblings and iterate through them, I am hoping for a more elegant solution that I may not be aware of. It would be ideal if there was some sort of querySelectorAll(..) selector manipulation that I could utilize, perhaps through an intersection of two invocations.

<div>
<h1>Title</h1>
<h2>Subitle</h2>
<p>Para 1 <a href="#">link</a></p>
<p>Para 2</p>
<ul><li>A list</li></ul>
<hr/>
<h2>Another subtitle</h2>
<p>this should not be found</p>
</div>

Answer №1

Here are a few potential solutions to consider:

const getChildElementsInRange1 = (parentElement, firstChildSelector, lastChildSelector) => {
  const elementsInRange = [];
  let currentElement = parentElement.querySelector(firstChildSelector)?.nextElementSibling;

  while (currentElement) {
    if (currentElement.matches(lastChildSelector)) {
      return elementsInRange;
    }

    elementsInRange.push(currentElement);
    currentElement = currentElement.nextElementSibling;
  }
  
  return [];
}

const getChildElementsInRange2 = (parentElement, firstChildSelector, lastChildSelector) => {
  const elementsAfterLastChild = parentElement
    .querySelectorAll(`${firstChildSelector} ~ ${lastChildSelector} ~ *`);
  
  if (elementsAfterLastChild.length === 0) {
    return [];
  }
  
  const elementsAfterFirstWithoutLast = parentElement
    .querySelectorAll(`${firstChildSelector} ~ *:not(${lastChildSelector})`);
  
  return _.difference(elementsAfterFirstWithoutLast, elementsAfterLastChild);
}

const containerElement = document.getElementById('container');

console.log(getChildElementsInRange1(containerElement, 'h2', 'hr'));
console.log(getChildElementsInRange2(containerElement, 'h2', 'hr'));
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0bcbfb4b1a3b890e4fee1e7fee2e1">[email protected]</a>/lodash.min.js"></script>

<div id="container">
  <h1>Title</h1>
  <h2>Subtitle</h2>
  <p>Paragraph 1 <a href="#">link</a></p>
  <p>Paragraph 2</p>
  <ul><li>A list</li></ul>
  <hr/>
  <h2>Another subtitle</h2>
  <p>This should not be found</p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing my CSS dropdown menu to not display properly?

I'm having trouble getting the dropdown to work when hovering over the li element with "portfolio" in the text. The code seems correct, but nothing happens when I try to hover over "Portfolio." Below is the code snippet: #navmenu ul { position: ...

How can I display a Bootstrap modal in Ember.js after rendering it in an outlet?

I'm facing a challenge in my Ember.js application where I need to trigger the opening of a Bootstrap modal from my ApplicationRoute upon calling the openModal action. This is what my ApplicationRoute looks like: module.exports = Em.Route.extend({ ...

`Ensuring uniform height for card titles`

So here's the scenario I'm dealing with: https://i.sstatic.net/4f7AR.png There seems to be an issue with alignment in the dark blue boxes when they are displayed in a flex container. The top box is not aligned properly with the one next to it. ...

Seeking assistance with basic Javascript/Jquery for Ajax on Rails 3 - can anyone help?

I've been diving into JavaScript and hit a roadblock. At the moment, I have a very basic gallery/image application. My goal is to create a functionality where clicking on an image will lead the user to a URL stored in my model data using AJAX. Additi ...

Select three random items from a string array list along with their corresponding indexes using TypeScript in Angular

Consider this example: I am working with a string array const groceries = [ 'milk', 'coriander', 'cucumber', 'eggplant', 'carrot', 'brinjal', 'on ...

Ways to loop through a collection of indexed elements

I am working with an array of indexed objects and my goal is to iterate through it in order to transform it into a new flattened array. Here is the initial array of objects: "attentionSchedules": [ { "room": "1", ...

How shouldjs makes value verification effortless for unordered arrays

In my express.js application, I'm currently using supertest and should.js as my preferred testing framework. However, I've encountered some difficulties when it comes to testing for specific values within an unordered array. After referring to t ...

How to achieve the functionality of multiple inheritance using Object.create()

Seeking insights on implementing multiple inheritance in JavaScript. Various methods exist, each with pros and cons. However, there lacks a comprehensive analysis of Object.create() presented in an understandable manner. After conducting experiments, I hav ...

Open the .exe file using an HTML link in Firefox browser

While working on a project using php / js / html, I encountered the need to launch a C# application from my web page without requiring any downloads. The challenge was that I primarily use Mozilla Firefox and could only find solutions involving ActiveXOb ...

Incorporate Vue into a template using variables and props

Currently in the process of building a vue app and wondering how I can seamlessly integrate it into a template while passing variables (props) into it. When I execute npm run dev, the app and all its components are coded with no issues. After running npm ...

Avoid displaying the homepage link in the menu on Grav

I'm working on my very first Grav website. Currently, I am in the process of creating a navigation menu and would like it to display links to all visible pages except for the homepage. The issue I'm facing is that the homepage appears as the fir ...

Accessing data in JSON format from a URL

I'm working on a website that analyzes data from the game Overwatch. There's this link () that, when visited, displays text in JSON format. Is there a way to use JavaScript to read this data and display it nicely within a <p> tag on my si ...

unable to display loading image prior to upload

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html lang="en"> <head> <title>Unique Prints</title> <meta charset="utf-8"> <meta name="viewport" conte ...

The Struggle with Bootstrap Accordion

I'm currently in the process of learning bootstrap. I copied the code for the 'Flush' Accordion from the bootstrap docs, but my version looks completely off. Despite linking the CSS stylesheet and JS Bundle, it doesn't seem to align pro ...

When submitting an Asp net mvc Form, some fields may not be posted as expected

I'm facing an issue with my ASP.NET MVC application form. Some fields that should be posted are missing, and I can't figure out why. <form id="FormRegistroUsuario" action="/Account/AdminSecurityUserAccountAdd"> <fieldset> ...

Slow rotation in CSS styling

.badge { -webkit-transform-style: preserve-3d; -webkit-perspective: 1000; position: relative; } .back, .front { position: absolute; -webkit-backface-visibility: hidden; -webkit-transition: -webkit-transform 1s ease-in; width: ...

Retrieve the previous cost from an Amazon product listing

While working with Python's BeautifulSoup to extract the previous price from an Amazon page, I encountered a problem where my code was displaying the current price instead of the previous one. This is the code snippet I tried: priceold = soup.find(cl ...

Is the npm mqtt module continuously running but not performing any tasks?

I'm relatively new to the world of JS, node.js, and npm. I am attempting to incorporate a mqtt broker into a project for one of my classes. To gain a better understanding of how it functions, I installed the mqtt module from npm. However, when I tried ...

Is there a way to manage specific HTML elements in Angular?

I am working on displaying a list of enable/disable buttons for different users. The goal is to show the appropriate button for each user based on their status - enabling if disabled and disabling if enabled. To achieve this, I have utilized the flags "use ...

Is it possible for style sheets to malfunction due to the presence of the TITLE attribute on <link> tags?

We are currently involved in the process of upgrading an outdated corporate intranet. The challenge is that our users primarily rely on IE8 and IE9, while most of our sites were designed to function with compatibility for browsers between IE5 - IE9. While ...