Javascript for adding a custom attribute to some elements
Given a section of HTML, can I selectively pick some types of elements (e.g., input) and add a custom attribute using JavaScript? I would also need to remove this attribute if it exists.
I have done this before using jQuery, but I'm unable to use it for this particular task.
Solution 1:
Accessing HTML attributes using the DOM
element.hasAttribute('foo');
element.getAttribute('foo');
element.setAttribute('foo', value);
element.removeAttribute('foo');
Solution 2:
<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'));