Reputation: 42474
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", .. ]
Upvotes: 0
Views: 323
Reputation: 324760
(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);
Upvotes: 2
Reputation: 125
var cPattern = new RegExp(/class[ \t]*=[ \t]*"[^"]+"/g);
var cMatches = data.match(cPattern).map(function(v){
return v.split("=")[1].replace(/^['"]|['"]$/g, "");
});
Upvotes: 0