Directly add an attribute as an element property

Here’s how I change the value of an existing attribute:

element.attribute = "value"

But is it OK to use the above method to create a new attribute?

You could use:

document.getElementById("element").setAttribute("name", "content");

AFAIK one is (normally) a shortcut for the other.

E.g.

element.attribute = "value"

is the same as:

element.setAttribute(attribute, "value");

So I would say yes, it’s fine to use the first method to create a new attribute.

Thanks for the confirmation! :slight_smile:

Just the usual warnings about old IE, if you’re supporting, being safer with the pure dot (.) notation. Specifically IE up to 8 (and totally not sure what’s been fixed in 9) had trouble with both getAttribute and setAttribute. Which is why there’s lots of code floating around out there with just .attribute. Or why some people will load up the whole of jQuery just to get el.attr('some attr);

I’m not. Thanks for the advice, though! :slight_smile: