DOM Manipulating Attributes Setting an attribute


Some attributes are directly accessible as properties of the element (e.g. alt, href, id, title and value).

document.querySelector("a").href = "#top";

Other attributes, including data-attributes can be set as follows:

document.querySelector("a").setAttribute("aria-label", "I like turtles");

Data attributes can also be set using dataset (modern browsers)

var a = document.querySelector("a");
a.dataset.test = "123";
a.dataset['test-2'] = "456";

results in

<a href="#" data-test="123" data-test-2="456">Widget</a>