Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.

Solution 2:

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).

Solution 3:

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.

Post a Comment for "Javascript Remove All Content Between Some Tags"