Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!!

like image 916
Philip Southwell Avatar asked Dec 14 '14 06:12

Philip Southwell


People also ask

Can JavaScript add HTML elements?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.

Can I add my own attributes to HTML elements?

If you want to define your own custom attributes in HTML, you can implement them through data-* format. * can be replaced by any of your names to specify specific data to an element and target it in CSS, JavaScript, or jQuery.

What is setAttribute in JavaScript?

Element.setAttribute() Sets the value of an attribute on the specified element. If the attribute already exists, the value is updated; otherwise a new attribute is added with the specified name and value. To get the current value of an attribute, use getAttribute() ; to remove an attribute, call removeAttribute() .


1 Answers

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">
like image 195
Sampath Liyanage Avatar answered Oct 13 '22 00:10

Sampath Liyanage