简体   繁体   中英

How can I insert a value in the value attribute of a div with JavaScript?

How can I insert a value in the value attribute of a div using Internet Explorer 9. I tried a lot of JavaScript functions but I can only modify the content of the div, not the value attribute.

<div id="mydiv" value="somevalue">

</div>

This is my code that change the content not the value attribute.

var div = document.getElementById('mydiv');
div.innerHTML = "something";
div.setAttribute('value', 'whateveryouwant');

参考: https : //developer.mozilla.org/en/docs/Web/API/Element/setAttribute

value is not valid attribute of div, by using setAttribute() you can set any attribute to div which doesn't check if attribute is valid or not. value can be added for elements like input as below:

 var div = document.getElementById('myinput'); div.value="something"; 
 <div id="mydiv"> <input value="" id="myinput"/> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM