0

I'm trying to match a span element with a certain class name and everything that comes between its start and finish.

My regex is /<\/?(span)[^>]*"myClass".*?<\/span>/gi. It works on <span class="myClass">...</span>, but it fails on something like below, only extending to the first </span>:

<span class="myClass"> ... <span class="anything else"> ... </span> ... </span>

How can I match it all from beginning to end?

Iryn
  • 255
  • 2
  • 5
  • 13

3 Answers3

2

This regex should do the job for you:

/span\s(?:class="myClass")>(.*)<\/span\>/

var txt = '<span class="myClass"><span class="anything else"></span></span>';
txt.match(/span\s(?:class="myClass")>(.*)<\/span\>/)

Output

["span class="myClass"><span class="anything else"></span></span>", "<span class="anything else"></span>"]

var txt = '<span class="myClass">foobar</span>';
txt.match(/span\s(?:class="myClass")>(.*)<\/span\>/)

Output

["span class="myClass">foobar</span>", "foobar"]

Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Well, it simply extends to the last ``, which may be outside of the desired ``. For example, it matchs all of the following `foobar`. – Iryn Nov 21 '13 at 16:30
  • You need to have a very good and serious reason to use regexp instead of the DOM api to get a html element. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Robert Nov 21 '13 at 16:35
  • @Robert I don't disagree at all, just trying to answer the question that was posed. – Rob M. Nov 21 '13 at 16:46
1

It is bad practice to use regexp for parsing html. You can work with DOM instead. This should do that you want:

var value = document.getElementsByClassName("myClass")[0].innerHTML;
Artem Vyshniakov
  • 16,355
  • 3
  • 43
  • 47
0

you dont need REGEX only Jquery Find suppose that we will ad a div

<div id="myid"><span class="myClass"> ... <span class="anything else"> ... </span> ... </span></div>

spanList = $('myid').find('.myClass, .anything else'); 
Hichem
  • 1,111
  • 11
  • 30