Javascript for adding a custom attribute to some elements

Accessing HTML attributes using the DOM

element.hasAttribute('foo');
element.getAttribute('foo');
element.setAttribute('foo', value);
element.removeAttribute('foo');

<div class="first-div">
<p class="first-p">Hello!
</p>
</div>

Adding attribute via javascript:

var myDiv= document.getElementsByClassName("first-div")[0];
var myp= myDiv.children[0];
nyp.setAttribute('myAttribute','valueForAttribute');

getting the attribute via javascript:

   console.log(myp.getAttribute('myAttribute'));

Tags:

Javascript