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?

1
  • 1
    relevant Commented Nov 21, 2013 at 16:11

3 Answers 3

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"]

Sign up to request clarification or add additional context in comments.

3 Comments

Well, it simply extends to the last </span>, which may be outside of the desired <span class="myClass">. For example, it matchs all of the following <span class="myClass">foobar</span><span></span>.
You need to have a very good and serious reason to use regexp instead of the DOM api to get a html element. stackoverflow.com/questions/1732348/…
@Robert I don't disagree at all, just trying to answer the question that was posed.
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;

Comments

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'); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.