ONYX
ONYX

Reputation: 5859

get attributes from html string name value pairs

I have a string like this

'<img id="1" data-name="test" src="img_01.jpg" />'

What I would like to do is extract the attributes in name value pairs from the string then create the element and apply the attributes

what I have is this so far but I don't know how to extract attribute name and value

createNode = function(a, b) {
  let name = null;
  let el = null;

  if(/<[a-z][\s\S]*>/i.test(a)) {
    name = a.match(/(\w+)/i)[1];
    el = document.createElement(name);
    // get attributes and apply them
    return el;
  } 
}

createNode('<img id="1" data-name="test" src="image_01.jpg" />');

Upvotes: 0

Views: 874

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

You might use DOMParser to parse the HTML string into an actual element, and then just return that element:

const createNode = (htmlStr) => {
  const doc = new DOMParser().parseFromString(htmlStr, 'text/html');
  const element = doc.body.children[0];
  return element;
};

const img = createNode('<img id="1" data-name="test" src="image_01.jpg" />');
console.log(img.id);

If you had to go the regex route, then a possibility is:

createNode = function(a, b) {
  const [, tagName, attribStr] = a.match(/^<(\S+)(.*)>$/);
  const element = document.createElement(tagName);
  let match;
  const re = / *([^=]+)="([^"]*)"/g;
  while (match = re.exec(attribStr)) {
    const [, attribName, attribVal] = match;
    element.setAttribute(attribName, attribVal);
  }
  return element;
}

const img = createNode('<img id="1" data-name="test" src="image_01.jpg" />');
console.log(img.outerHTML);

Upvotes: 1

Related Questions