Binita Gyawali
Binita Gyawali

Reputation: 256

Javascript split the HTML attributes and value

I have a list of javascript string with HTML tags and want to split the tags.

<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />
<section id = "test">

I tried to split by double quotes (") but getting only

class=", logo"

I want to split in the following array

[class="logo"], [src="http://i.imgur.com/z38lrml.png"],[height="60px"]

and so on for the next line.

Is there anyway to separate?

Thank you

Upvotes: 0

Views: 1764

Answers (2)

random
random

Reputation: 7891

const attributes = document.querySelector('img').getAttributeNames();
const img = document.querySelector('img');

const output = [...attributes].map((attr) => {
  const val = img.getAttribute(attr);
  return `${attr}" = "${val}`;
});

console.log(output);
<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />

Edit --

If your html is a string, use DOMParser to convert it into html.

const str = `<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />
<section id = "test">`;

const dom = new DOMParser().parseFromString(str, 'text/html');

let output = [];
[...dom.body.children].forEach((node) => {
    const attributes = node.getAttributeNames();
    output.push([...attributes].map((attr) => {
        const val = node.getAttribute(attr);
        return `${attr}" = "${val}`;
    }));
})

console.log(output);

Upvotes: 0

junvar
junvar

Reputation: 11574

It seems your HTML tag is actually just a string? In that case, you can use regex:

let html = '<img class="logo" src="http://i.imgur.com/z38lrml.png" height="60px" />';
let attributes = html.match(/[\w-]+="[^"]*"/g);
console.log(attributes);

Upvotes: 2

Related Questions