Documentation and Books

Recent site activity

Web Development‎ > ‎JavaScript‎ > ‎

Is it allowed to add custom attributes to elements?

Yes this is allowed, however you need to retrieve and set the attributes using the getAttribute and setAttribute methods:

<html>
<head>
<script type="text/javaScript">
function doAttributeChange() {
var myLink = document.getElementById("myLink");

// Display the attribute value
alert(myLink.getAttribute('extraAttr'));

// Change the value of the attribute.
myLink.setAttribute('extraAttr', 'value2');

// Display the attribute value again.
alert(myLink.getAttribute('extraAttr'));
}
</script>
</head>
<body>
<a id="myLink" extraAttr="value1">Link!</a>
<br/>
<input type="button" onclick="doAttributeChange();" value="Do change!"/>
</body>
</html>