javascript - Regex match HTML attributes names -
i have following element stored string:
<div class="some-class" id="my-id" data-theme="black"> <strong data-animation="fade" disabled>hello world!</strong> </div>
i want extract attributes names this:
["class", "id", "data-theme", "data-animation", "disabled"]
this tried do, values , dosent match data-animation , disabled:
http://jsbin.com/hibebezibo/edit?js,console
edit:
manged attributes using:
[\w-]+(?=\s*=\s*".*?")
but still cant "disabled" prop.
can explain me how achieve this? thanks!
using below regex benefits positive lookahead able match attributes' names:
[ ][\w-]+(?=[^<]*>)
note: adding -
character class must.
javascript code:
const htmlelement = `<div class="some-class" id="my-id" data-theme="black"> <strong data-animation="fade" disabled>hello world!</strong> </div>` console.log(htmlelement.match(/ [\w-]+(?=[^<]*>)/g).map(function(element) { return element.trimleft(); }));
however it's not bulletproof can match words following >
. e.g:
<strong data-animation="fade" disabled>hello world!></strong>
so it's recommended accomplish such task using dom functionalities:
var html = document.createelement('div'); html.innerhtml = '<div class="some-class" id="my-id" xlink:href data-theme="black"><strong data-animation="fade" disabled>hello world!</strong></div>'; var attrnodes = document.evaluate('//*/attribute::*', html, null, xpathresult.any_type, null) var nextattrnode = attrnodes.iteratenext() var arrattrs = []; while (nextattrnode) { arrattrs.push(nextattrnode.name) nextattrnode = attrnodes.iteratenext(); } console.log(arrattrs)
Comments
Post a Comment