Skip to content

Instantly share code, notes, and snippets.

@chrisgalard
Last active July 4, 2016 17:54
Show Gist options
  • Save chrisgalard/540ba91317c29440e47577f2fb1f9bbd to your computer and use it in GitHub Desktop.
Save chrisgalard/540ba91317c29440e47577f2fb1f9bbd to your computer and use it in GitHub Desktop.
A method to easily append a child with attributes and content to an element
Node.prototype.append = function(element, content, attribs) {
if (typeof element === 'string') {
element = document.createElement(element);
element.innerHTML = content ? content : '';
}
for (var attrib in attribs) {
if (attribs.hasOwnProperty(attrib)) {
element.setAttribute(attrib, attribs[attrib]);
}
}
return this.appendChild(element);
}
// Usage
var parent = document.querySelector('#parent');
parent.append('a', 'This is the content', {
class: 'child-a',
href:'http://nerdskills.io',
target: '_blank'
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment