简体   繁体   中英

javascript: getting class name from html code

I want to get class names from an html code using javascript, I can get the class names like this

var cPattern = new RegExp(/class[ \t]*=[ \t]*"[^"]+"/g);
var cMatches = data.match(cPattern);

but it is giving me results in array having values like

['class="hello-world"', 'class="any-name"' , ... ]

How to get resulting array with just values

["hello-world", "any-name", .. ]

没有
(source: nooooooooooooooo.com )

You have a DOM! Right there! You're in JavaScript, the DOM is right there! There! Look, I'm pointing at it! ... You can't see my hand? Okay then...

var tmp = document.createElement('div');
tmp.innerHTML = data;
var elementsWithClassNames = tmp.querySelectorAll("[class]");
var classNames = [], l = elementsWithClassNames.length, i;
for( i=0; i<l; i++) classNames[i] = elementsWithClassNames[i].className;

console.log(classNames);
var cPattern = new RegExp(/class[ \t]*=[ \t]*"[^"]+"/g);
var cMatches = data.match(cPattern).map(function(v){
    return v.split("=")[1].replace(/^['"]|['"]$/g, "");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM