Skip to content

Instantly share code, notes, and snippets.

@bgrins
Last active December 20, 2015 15:39
Show Gist options
  • Select an option

  • Save bgrins/6156133 to your computer and use it in GitHub Desktop.

Select an option

Save bgrins/6156133 to your computer and use it in GitHub Desktop.
Thoughts on attribute parsing for devtools inspector

I want to make a function that takes in id="one" class='two' and converts it to [{name: "id", value: "one" }, { name: "class", value: "two" }]. I have a little more information and small demo of what I am trying to do at this link: http://fiddle.jshell.net/bgrins/hhSXx/show/.

attribute-parsing

/*
Trying with nsIParserUtils.parseFragment, but bumping into two issues:
1) It seems to drop unknown/custom attributes.
2) Also, it prunes out duplicate attributes. Ideally if a user typed in class="1" class="2" it would still show both of them so they could resolve the problem manually rather than just removing the second one
*/
var body = document.implementation.createHTMLDocument().createElement("body");
var nsIParserUtils = Components.classes["@mozilla.org/parserutils;1"].getService(Components.interfaces.nsIParserUtils);
var fragmentStr = "<div customattribute='true' disabled class='&lt;<\">i'></div>";
var parsedBody = nsIParserUtils.parseFragment(fragmentStr, 0, false, null, body);
parsedBody.childNodes[0].outerHTML;
/*
<div disabled="" class="<<&quot;>i"></div>
*/
/*
Also trying with element.innerHTML = "<div " + attr + "></div>"
1) It handles unknown/custom attributes
2) It also prunes out duplicates
3) There may be some security / performance issues invloved with running this on user generated strings
*/
var div = document.implementation.createHTMLDocument().createElement("div");
var attr = "customattribute='true' disabled class='&lt;<\">i'";
attr = attr.replace(/</g, "&lt;").replace(/>/g, "&gt;");
div.innerHTML = "<div " + attr + "></div>";
div.innerHTML;
/*
<div customattribute="true" disabled="" class="<<&quot;>i"></div>
*/
id="hi"             <span id="hi"></span>
id="h<i"            <span id="h<i"></span>
id='hi'             <span id="hi"></span>
id='hi' a           <span id="hi" a></span>
id='hi' a=""        <span id="hi" a></span>
id='hi' a=b         <span id="hi" a="b"></span>
id='hi' a=b'        <span id="hi" a="b"></span>
id='hi' a=b'        <span id="hi" a="b'"></span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment