Philip Southwell
Philip Southwell

Reputation: 385

How to add attribute to HTML element using javascript

Using javascript (preferably not jquery) I'm trying to change the line:

<input type="number" name="price" required="" id="id_price">

into

<input type="number" name="price" required="" id="id_price" step="any">

I know the solution's got to be easy but I just can't crack it. Help would be much appreciated!!

Upvotes: 14

Views: 38220

Answers (1)

Sampath Liyanage
Sampath Liyanage

Reputation: 4896

As torazaburo suggests in the comment you can do it in one step with setAttribute() method

document.getElementById("id_price").setAttribute("step","any");
<input type="number" name="price" required="" id="id_price">


OR

First create the attribute and set the value. Then add it to the element..

var attr = document.createAttribute('step');
attr.value="any";
document.getElementById("id_price").setAttributeNode(attr);
<input type="number" name="price" required="" id="id_price">

Upvotes: 34

Related Questions