6

I have a div tag, nested within many span and div tags.

Now I want a regular expression in JavaScript which will strip the div tags and get the content inside it.

3
  • 1
    Do you really need to work on strings or can you work with the DOM? And can you give an example? Commented May 13, 2010 at 12:05
  • 1
    you should probably use an html parser, not regexes.... see stackoverflow.com/questions/1732348/… in javascript you should be able to use DOM accessor functions.. Commented May 13, 2010 at 12:05
  • Here is a RegEx that will match your needs: (!?(<.*?>)|[^<]+)\s* it works for all tags that are encapsulated with < > Commented Dec 29, 2021 at 10:38

2 Answers 2

6

You want to remove a <div> element from your document?

First things first; learn the DOM!

var aReferenceToMyDiv = document.getElementById('foo'); aReferenceToMyDiv.parentNode.removeChild(aReferenceToMyDiv); 

... will remove the <div> element when applied to the following DOM structure:

<div id="foo"> <span>...</span> other stuff... </div> 
Sign up to request clarification or add additional context in comments.

Comments

3

Regular expressions can't handle nesting, at least JavaScript regexes can't (and those that can, like .NET and PCRE, aren't easy to handle).

This could only work if there is just one outermost <div> tag - then the regular expression

/<div>.*<\/div>/s` 

will match everything from the very first <div> to the very last </div> in your document.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.