angry kiwi
angry kiwi

Reputation: 11485

Get all class names inside class attributes

let string = `
    <div class="camera"></div>
    <div class="cinema alibaba"></div>
`

I have a string like above.

How to get all class names and put them into an array?

Expected result: [camera, cinema, alibaba].

Upvotes: 0

Views: 85

Answers (2)

Daria Pydorenko
Daria Pydorenko

Reputation: 1802

You can do it with regex:

let string = `
    <div class="camera"></div>
    <div class="cinema alibaba"></div>
`

let pattern = /.+?class="(.+?)".+?/g

var match = pattern.exec(string);
var arr = []

while (match != null) {
  match[1].split(" ").forEach(x => arr.push(x));
  match = pattern.exec(string)
}

console.log(arr);

Upvotes: 4

Hyyan Abo Fakher
Hyyan Abo Fakher

Reputation: 3527

Not the most optimal solution but you can attache the HTML string to a temp element, then select all elements to get the class names

let str = `
    <div class="camera"></div>
    <div class="cinema alibaba"></div>
`

let temp = document.createElement('div')
temp.style.display = 'none';
temp.innerHTML = str;

items = temp.querySelectorAll('*')
let classes = [];
items.forEach(item => {
  classes = classes.concat(item.className.split(" "))
});

console.log(classes);

Upvotes: 3

Related Questions