60

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.

4 Answers 4

108

Accessing HTML attributes using the DOM

element.hasAttribute('foo');
element.getAttribute('foo');
element.setAttribute('foo', value);
element.removeAttribute('foo');
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

-2
el.attribute = value

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

4 Comments

This sets a property to the HTMLElement object. It doesn't set an attribute. Use setAttribute ( name, value ).
What's the difference practically?
@GergőHorváth Maybe when using querySelector, because you can query in attributes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.