1

Say, I have a string like

<body class="body-element" style="background: red;"><div class="inner">...</div></body>

I would like to extract all attributes of body tag. As for jQuery parsing ignores body tag I can't use it. So, how to do it using regular expressions?

I need to extract attributes only from the body tag.

4
  • 1
    Consider document.querySelector('body').attributes instead. Commented Apr 20, 2019 at 17:56
  • @Walk is this solution cross-platform? And I don't have any document object, it's just a string. Commented Apr 20, 2019 at 17:57
  • It is developer.mozilla.org/en-US/docs/Web/API/Element/… Commented Apr 20, 2019 at 18:00
  • In that case you can parse it first: (new DOMParser()).parseFromString('<body class="body-element" style="background: red;"></body>', 'application/xml').querySelector('body').attributes. Check developer.mozilla.org/en-US/docs/Web/API/DOMParser Commented Apr 20, 2019 at 18:02

2 Answers 2

3

Use a DOMParser, get the .body and then its .attributes.

var s = '<body class="body-element" style="background: red;"><div>...</div></body>';

var attrs = new DOMParser().parseFromString(s, "text/html").body.attributes;

for (const a of attrs) console.log("%s = %s", a.name, a.value);

Sign up to request clarification or add additional context in comments.

Comments

0

This RegEx might help you to divide your input HTML string into two groups and get the desired attributes:

([a-z]+)="([A-Za-z0-9_\-\:\s;]+)

You might add other chars to [A-Za-z0-9_\-\:\s;], if necessary.

enter image description here

1 Comment

Thanks but I need to extract attributes only from body tag. This regex will catch all of them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.