Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add an HTML element starting after one and finishing before another one

Can’t find a solution to my problem, hope you can help :

I got this :

<hr id="first-hr" /> 
<p> lorem ipsum </p>
<span> bla bla bla </span>
<hr />

I’d like to, automatically in javascript, add a parent to anything beetween an identified hr and the next one

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<hr id="first-hr" /> 
<div id="my-new-div">
        <p> lorem ipsum </p>
        <span> bla bla bla </span>
</div>
<hr />

The goal is to add some style to this div by adding a class. If it is simpler to retrieve all elements between the identified hr and the next one and add a class to them without adding a parent, I’m fine with that too!

Thanks ! <3

>Solution :

This code will loop over all the siblings of the first-hr element, appending them to a div which is inserted after the first-hr element:

const hr = document.getElementById('first-hr')
let next = hr.nextSibling
const div = document.createElement('div')
hr.parentNode.insertBefore(div, next)
div.setAttribute('id', 'my-new-div')
while (next) {
  let node = next
  next = next.nextSibling
  div.appendChild(node)
  if (!next || next.nodeName == 'HR') break
}
#my-new-div {
  background-color: lightblue;
}
<hr id="first-hr">
<p id="x"> lorem ipsum </p>
<span> bla bla bla </span>
<hr />

Here’s another way to do it which doesn’t have any explicit looping in it, but of course it is present, hidden inside calls to indexOf and findIndex:

const hr = document.getElementById('first-hr')
let siblings = [...hr.parentNode.childNodes]
siblings = siblings.slice(siblings.indexOf(hr)+1)
const nexthr = siblings.findIndex(n => n.nodeName == 'HR')
siblings = siblings.slice(0, nexthr)
const div = document.createElement('div')
div.setAttribute('id', 'my-new-div')
div.append(...siblings)
hr.parentNode.insertBefore(div, hr.nextSibling)
#my-new-div {
  background-color: lightblue;
}
<hr id="first-hr">
<p id="x"> lorem ipsum </p>
<span> bla bla bla </span>
<hr />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading