Skip to content Skip to sidebar Skip to footer

How To Get Style="i Want The Css Code" Using Regexp (javascript)

var text = '..hellohello...

Solution 1:

Make a temporary element and use innerHTML, then getElementsByTagName and getAttribute('style') if it's a string like that.

If it's a reference to a DOM element skip the innerHTML part.

var d = document.createElement('div'), 
    text = '..<anything><anything style="color:red;">hello</anything><anything style="color:blue; font-size:1em;">hello</anything></anything>...', 
    styles = [];
    d.innerHTML=text;
    var els = d.getElementsByTagName('*');
    for ( var i = els.length; i--; ) {  
        if ( els[i].getAttribute('style') ) { 
           styles.push(  els[i].getAttribute('style')  )
        }
    }
    styles

The jQuery would be..

$(text).find('*').map(function() { returnthis.getAttribute('style') })

Solution 2:

As has already been mentioned, it's not a great idea to use regular expressions for parsing HTML.

However, if you're determined to do it that way, this will do the job for you:

var matches = text.match(/\bstyle=(['"])(.*?)\1/gi);
var styles = [];
for(var i = 0; i < matches.length; i++) {
    styles.push(matches[i].substring(7, matches[i].length - 1));
}

Solution 3:

meder has already given the correct answer, but since a regex solution was desired I'll give one. All the usual warnings about parsing a nonregular language like HTML (or SGML, or XML) with regular expressions apply.

/<[a-z]+(?:\s+ [a-z]+\s*=\s*(?:[^\s"']*|"[^"]*"|'[^']*'))\s+style\s*=\s*"([^"]*)">/g

Post a Comment for "How To Get Style="i Want The Css Code" Using Regexp (javascript)"