Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

223
Views
Remove DIV's innerHTML until a <p> tag

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!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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;
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!