How to Add/Update an Attribute to an HTML Element Using JavaScript

How to add/update an attribute to an HTML element using JavaScript?

You can read here about the behaviour of attributes in many different browsers, including IE.

element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, then maybe
element.attributeName = 'value' might work.

How to update value of an attribute of an element, then trigger click on it?

You can simply use :

$( "#image" ).trigger( "click" );

For more information on jQuery trigger click here.

Update HTML attribute from appended HTML element

When creating the select block

"<select id='SEL"+index+"' onChange='updateName2(index)'>"+

You use the index variable in its id, but in the function in onChange you just use index as a string, which doesn't refer to the variable correctly. This means that you're running document.getElementById("SEL" + undefined), which returns null (as such an element does not exist).

Try this instead:

"<select id='SEL"+index+"' onChange='updateName2(" + index + ")'>"+

Javascript Update Attribute

You can use dataset or setAttribute,

// datasetdocument.getElementById('focusedInput').dataset.filter = "test";
// setAttributedocument.getElementById('focusedInput').setAttribute('data-filter', 'test-1');
<input type="text" name="araButon" onKeyUp="return arama()" class="form-control filter" data-filter="app" id="focusedInput" />

Change HTML5 data attribute when updating an input field

I just code for you in my FIDDLE. Use this JSFIDDLE. It will work properly. I hope this is the one you want now.

HTML5

<input id="text" type="text"/>
<br/><br/>
<div id="result" data-foo="">This is the div with `data-foo` attribute. While you typing this div `data-foo` attribute will change as input valu. If you want to check it. Just click on below button.</div>
<br/>
<button id="test">What is my DIV `data-foo` now?</button>

jQuery

//FOR TESTING - This function will help you to test the below function is working or not
$("#test").click(function(){
var value = $('#result').attr('data-foo');
alert(value);
});

//This function will auto change `data-foo` while you typing
$("#text").keyup(function(){
var text = $(this).val();
$("#result").attr('data-foo',text);
});

Use it when DOM is ready.

If you need my help. Please find me any of social network by searching yeshansachithak.



Related Topics



Leave a reply



Submit