删除 DIV 的 innerHTML 直到 <p> 标记
Remove DIV's innerHTML until a <p> tag
假设我有一个div
,如下:
<div id="mainDIV">Area to remove <p>Area to not remove</p></div>
我想删除 div 的 content/innerHTML 直到 p
标签。
我尝试通过以下方式删除它:
document.getElementById("mainDiv").innerHTML = ""
虽然这删除了我想删除的区域,但它也删除了 p
元素及其内容。
有办法吗?谢谢!
可以获取
的内容,然后将其插入到#mainDIV的内部HTML,如:
document.getElementById('mainDIV').innerHTML = document.getElementById('mainDIV').querySelector('p').outerHTML;
假设要删除的东西总是第一个 text node you can remove that first child 节点。
const mainDiv = document.querySelector('#mainDIV');
mainDiv.removeChild(mainDiv.firstChild);
<div id="mainDIV">Area to remove <p>Area to not remove</p></div>
但也要注意拼写。 mainDiv
不是 mainDIV
.
您可以像这样使用 'split' 函数:
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;
你 div 的 innerHTML 现在是“不删除的区域”(加上 p 标签)
另请注意,拆分将删除 p 标签的开头,因此稍后添加即可
假设我有一个div
,如下:
<div id="mainDIV">Area to remove <p>Area to not remove</p></div>
我想删除 div 的 content/innerHTML 直到 p
标签。
我尝试通过以下方式删除它:
document.getElementById("mainDiv").innerHTML = ""
虽然这删除了我想删除的区域,但它也删除了 p
元素及其内容。
有办法吗?谢谢!
可以获取
的内容,然后将其插入到#mainDIV的内部HTML,如:
document.getElementById('mainDIV').innerHTML = document.getElementById('mainDIV').querySelector('p').outerHTML;
假设要删除的东西总是第一个 text node you can remove that first child 节点。
const mainDiv = document.querySelector('#mainDIV');
mainDiv.removeChild(mainDiv.firstChild);
<div id="mainDIV">Area to remove <p>Area to not remove</p></div>
但也要注意拼写。 mainDiv
不是 mainDIV
.
您可以像这样使用 'split' 函数:
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;
你 div 的 innerHTML 现在是“不删除的区域”(加上 p 标签)
另请注意,拆分将删除 p 标签的开头,因此稍后添加即可