5

I am curious if it is possible using javascript to take an existing html statement like

<input id="name">

and transform it to

<input id="name" asdf="fdsa">

5 Answers 5

8

Yes , try this:

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

Pure Vanilla Javascript!

Sign up to request clarification or add additional context in comments.

1 Comment

setAttribute("event.stopPropagation()") The above syntax is not working.. what's the solution to this..??
2

For storing data in an element you may also use dataset property.

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

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

Comments

1

First, get 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 Comment

If it is a custom attribute it is good to prepend it with "user-"
0

you can do it using jquery also

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

Comments

0

Yes, it is possible.

Vanilla JS:

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

jQuery:

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

Comments

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.