Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you wanted a framework-esq syntax (<strong>Note:</strong> IE 8+ support only), you could extend the <code>Element</code> prototype and add your own <code>setAttributes</code> function:</p> <pre><code>Element.prototype.setAttributes = function (attrs) { for (var idx in attrs) { if ((idx === 'styles' || idx === 'style') &amp;&amp; typeof attrs[idx] === 'object') { for (var prop in attrs[idx]){this.style[prop] = attrs[idx][prop];} } else if (idx === 'html') { this.innerHTML = attrs[idx]; } else { this.setAttribute(idx, attrs[idx]); } } }; </code></pre> <p>This lets you use syntax like this:</p> <pre><code>var d = document.createElement('div'); d.setAttributes({ 'id':'my_div', 'class':'my_class', 'styles':{ 'backgroundColor':'blue', 'color':'red' }, 'html':'lol' }); </code></pre> <p>Try it: <a href="http://jsfiddle.net/ywrXX/1/" rel="nofollow">http://jsfiddle.net/ywrXX/1/</a></p> <p>If you don't like extending a host object (<a href="http://perfectionkills.com/whats-wrong-with-extending-the-dom/" rel="nofollow">some are opposed</a>) or need to support IE7-, just use it as a function</p> <p>Note that <code>setAttribute</code> will not work for <code>style</code> in IE, or event handlers (you shouldn't anyway). The code above handles <code>style</code>, but not events.</p> <p><strong>Documentation</strong></p> <ul> <li>Object prototypes on MDN - <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/prototype" rel="nofollow">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/prototype</a></li> <li><code>setAttribute</code> on MDN - <a href="https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute" rel="nofollow">https://developer.mozilla.org/en-US/docs/DOM/element.setAttribute</a></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload