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
<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
CodePudding user response:
At first <hr>
tag is not closeable
https://www.w3schools.com/tags/tag_hr.asp#:~:text=The tag defines a,change
const firstHr = document.querySelector('#first-hr')
const innerHtml = firstHr.innerHTML
const parrent = document.createElement('div')
parrent.id = 'my-new-div'
firstHr.innerHTML = ''
firstHr.append(parrent)
parrent.innerHTML = innerHtml
CodePudding user response:
If you want to add class in a div tag insert this one inside it should look like
<div id="my-new-div ">
.. once you are done try adding the class to css
.text-container{
background-color: aqua;
margin
}
<hr id="first-hr" />
<div id="my-new-div" >
<p> lorem ipsum </p>
<span> bla bla bla </span>
</div>
<hr />
if you want to style h1
add class and style it to css
CodePudding user response:
<hr id="first-hr" />
<p > lorem ipsum </p>
<span > bla bla bla </span>
<hr />
document.querySelectorAll("hr#first-hr > .add-styles").forEach(tag => {
tag.classList.add("some-class") //or .remove()
})
CodePudding user response:
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:
hr = document.getElementById('first-hr')
next = hr.nextSibling
div = document.createElement('div')
hr.parentNode.insertBefore(div, next)
div.setAttribute('id', 'my-new-div')
while (next) {
next = next.nextSibling
div.appendChild(next.previousSibling)
if (!next || next.nodeName == 'HR') break
}
console.log('done!')
#my-new-div {
background-color: lightblue;
}
<hr id="first-hr">
<p id="x"> lorem ipsum </p>
<span> bla bla bla </span>
<hr />