Solution 1 :

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.

Solution 2 :

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;

Solution 3 :

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

Problem :

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!

Comments

Comment posted by Andy

Your code won’t work initially because you have the wrong id for the element. But also, probably, you shouldn’t be treating HTML as a string to manipulate, but as a tree of DOM elements that have lots of methods to manipulate them.

By