I have the following element stored as a String:
JavaScript
x
4
1
<div class="some-class" id="my-id" data-theme="black">
2
<strong data-animation="fade" disabled>Hello world!</strong>
3
</div>
4
I want to extract all the attributes names like this:
JavaScript
1
2
1
["class", "id", "data-theme", "data-animation", "disabled"]
2
This is what I tried to do, but I get also the values and dosent match the data-animation and disabled:
http://jsbin.com/hibebezibo/edit?js,console
EDIT:
Manged to get attributes using:
JavaScript
1
2
1
[w-]+(?=s*=s*".*?")
2
But I still cant get the “disabled” prop.
Can someone explain me how to achieve this? Thanks!
Advertisement
Answer
Using below regex which benefits from a positive lookahead you are able to match attributes’ names:
JavaScript
1
2
1
[ ][w-]+(?=[^<]*>)
2
Note: Adding -
to character class is a must.
javascript code:
JavaScript
1
7
1
const HtmlElement = `<div class="some-class" id="my-id" data-theme="black">
2
<strong data-animation="fade" disabled>Hello world!</strong>
3
</div>`
4
5
console.log(HtmlElement.match(/ [w-]+(?=[^<]*>)/g).map(function(element) {
6
return element.trimLeft();
7
}));
However it’s not bulletproof as it can match words following a >
. E.g:
JavaScript
1
2
1
<strong data-animation="fade" disabled>Hello world!></strong>
2
So it’s recommended to accomplish such a task using DOM functionalities:
JavaScript
1
11
11
1
var html = document.createElement('div');
2
html.innerHTML = '<div class="some-class" id="my-id" xlink:href data-theme="black"><strong data-animation="fade" disabled>Hello world!</strong></div>';
3
var attrNodes = document.evaluate('//*/attribute::*', html, null, XPathResult.ANY_TYPE, null)
4
5
var nextAttrNode = attrNodes.iterateNext()
6
var arrAttrs = [];
7
while (nextAttrNode) {
8
arrAttrs.push(nextAttrNode.name)
9
nextAttrNode = attrNodes.iterateNext();
10
}
11
console.log(arrAttrs)