Javascript for adding a custom attribute to some elements

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

Accessing HTML attributes using the DOM

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

Solution 2 - Javascript

<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'));

Solution 3 - Javascript

el.attribute = value

is all there is to it. The attribute is created if it does not exist.

Solution 4 - Javascript

You can look here how to get and set the attribute.

https://jsfiddle.net/tuc57hbp/6/

to get attribute you must first get the <td> value. Then you must get it's input children using td.children[0] and set the input children attribute value using input.setAttirbute('dummy', 'value'). Then retrieve it using getAttribute('dummy').

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDotnetDudeView Question on Stackoverflow
Solution 1 - JavascriptLuis MelgrattiView Answer on Stackoverflow
Solution 2 - JavascriptOlaru AlinaView Answer on Stackoverflow
Solution 3 - JavascriptMachaView Answer on Stackoverflow
Solution 4 - JavascriptVictorView Answer on Stackoverflow