Iryn
Iryn

Reputation: 255

Javascript regex: matching a span element with a certain class, from beginning to end

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?

Upvotes: 0

Views: 4513

Answers (3)

Rob M.
Rob M.

Reputation: 36511

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

Upvotes: 2

Artem Vyshniakov
Artem Vyshniakov

Reputation: 16465

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;

Upvotes: 1

Hichem
Hichem

Reputation: 1182

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

Upvotes: 0

Related Questions