Home > Back-end >  Remove DIV's innerHTML until a <p> tag
Remove DIV's innerHTML until a <p> tag

Time:03-25

Let's say I have a div, as the following:

<div id="mainDIV">Area to remove <p>Area to not remove</p></div>

I want to remove the div's content/innerHTML until the p tag. I tried to remove it by the following:

document.getElementById("mainDiv").innerHTML = ""

While this removed the area I wanted to be deleted, it also removed the p element and it's content.

Is there a way to do this? Thanks!

CodePudding user response:

Assuming the thing to be removed will always be the first text node you can remove that first child node.

const mainDiv = document.querySelector('#mainDIV');
mainDiv.removeChild(mainDiv.firstChild);
<div id="mainDIV">Area to remove <p>Area to not remove</p></div>

But also watch your spelling. mainDiv is not mainDIV.

CodePudding user response:

You can get the content of <p> and then insert it into the inner HTML of #mainDIV, such as:

document.getElementById('mainDIV').innerHTML = document.getElementById('mainDIV').querySelector('p').outerHTML;

CodePudding user response:

you can use the 'split' function so like:

var your_div = document.getElementById("mainDiv");
//splits the innerHTML of the div at "<p>" and selects the inside p side
var just_the_p = your_div.innerHTML.split("<p>")[1];
your_div.innerHTML = "<p>" just_the_p;

you div's innerHTML now is "Area to not remove" (plus the p tag)

also note the split will remove the start of the p tag so just add it in later

CodePudding user response:

you have two choices whether you create a js function that loops over the elements inside THE div and deletes any element other than a p tag or you can control the space left between the div and the p tag with CSS using padding and margin

  • Related