You can add an attribute to an existing tag using javascript

I am curious if it is possible to use javascript to take an existing html-operator, for example

<input id="name"> 

and convert it to

 <input id="name" asdf="fdsa"> 
+4
source share
5 answers

Yes, try the following:

 document.getElementById("name").setAttribute("user-attr","Hello") 

Pure Vanilla Javascript!

+5
source

You can also use the dataset property to store data in an element.

 document.getElementById("name").dataset.someDataAttr = 'mydata'; 

This will result in an attribute named "data-some-data-attr".

+2
source

First enter the dom element:

 var element = document.getElementById("name"); 

Then set the attribute

 element.setAttribute("asdf", "fdsa"); 

If you are using jQuery

 $("#name").addr("asdf", "fdsa"); 
+1
source

you can do it using jquery also

 $('#name').attr('asdf','fdsa'); 
0
source

Yes it is possible.

Vanilla JS:

 document.getElementById('name').setAttribute('asdf','fdsa'); 

JQuery

 $("#name").attr("asdf","fdsa"); 
0
source

Source: https://habr.com/ru/post/1484339/


All Articles