简体   繁体   中英

JavaScript remove all content between some tags

I'd like to remove all content between two tags using JavaScript only (without jQuery or something similar). Also I can't modify content I want to delete.

For example for the code below:

<body>
<p>Remove me</p>
<a href="#">Me too</p>
<img src="But don't me!"/>
(...)

I want to delete everything between <body> and <img/> .

You can use something like this:

var children = document.body.childNodes;

for(var i = 0; i < children.length; i++)
{
    if(children[i].tagName == 'IMG')
        break;

    document.body.removeChild(children[i]);
}

Try it, it should work, but this is a strict example of exactly the same structure that you have in the example code. Generally, you get the parent element of the content you want removed. Then remove tags one by one, until you hit the tag that you don't want removed. This could work, but I wouldn't recommend it - wrap the content in a div or something like that and remove just this one tag. Makes things much simpler both for you and others who might need to take a look at the code.

Since you can't modify the HTML or use a library, you could try getElementsByTagName to retrieve the nodes

  • getElementsByTagName("p")[0]
  • getElementsByTagName("a")[0]

Then it depends on if you want them tags to still be there, but without content, or if you want the tags to be removed as well. In case you want the content to be removed but for some reason keep the empty nodes, try setting

  • var aNode = document.getElementsByTagName('a')[0];
  • aNode.innerHtml="";

If you want to remove the complete node, do as previously mentioned:

  • var pNode = document.getElementsByTagName('p')[0];
  • pNode.parentNode.removeChild(pNode);

Of course, you have to keep an eye on the DOM not changing in the future, as this might ruin the solution.

Based on the premise:

I'd like to remove all content between two tags using JavaScript only (without jQuery or something similar).

and the comment above:

Also let's say that I can't modify content

If you cannot add id's to the elements or wrap them in some container, I can see two solutions.

  • Use getElementByTagName() to locate the img-tag and then remove all child nodes prior to it.
  • Use document.removeChild() and use fixed child node indices (if the indices of the items are fixed)

Both solutions are heavily dependent on the DOM not changing in the future. I would strongly recommend to use jQuery or some other framework to make things easier (and cross-browser compatible).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM