Skip to content

Instantly share code, notes, and snippets.

@phloe
Last active October 3, 2015 18:07
Show Gist options
  • Save phloe/2500339 to your computer and use it in GitHub Desktop.
Save phloe/2500339 to your computer and use it in GitHub Desktop.
Create elements from selectors
var dom = function (selector) {
var element, props, el,
id, className, attributes,
attribute, name, value, i;
while (selector.length > 1) {
props = selector.match(/(?:\s|^)([^.#\[\s]+|)(#[^.\[\s]+|)((?:\.[^.\[\s]+)+|)((?:\[[^\]]+\])+|)$/);
el = document.createElement(props && props[1] || "div");
if (element) {
el.appendChild(element);
}
element = el;
if (props) {
selector = selector.slice(0, -props[0].length);
id = props[2];
className = props[3];
attributes = props[4];
if (id || className || attributes) {
attributes = attributes && attributes.slice(1, -1).split("][") || [];
if (id) {
attributes.push("id=" + id.slice(1));
}
if (className) {
attributes.push("class=" + className.slice(1).replace(".", " "));
}
i = attributes.length;
while (i--) {
attribute = attributes[i].split("=");
name = attribute[0];
value = (1 in attribute) ? attribute[1] : name;
if (name in element) {
element[name] = value;
}
else {
element.setAttribute(name, value);
}
}
}
}
}
return element;
};
var el = dom("table.foo[title=Very short description of content] tbody tr td[innerHTML=hello]");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment