简体   繁体   中英

Javascript: Set element value?

I would like to set a value of a <label> , like so:

<label for="idname">Value here...</label>

with Javascript. I have already done this, for the for attribute:

element.setAttribute("for", "idname");

is there something like element.setValue() that I can use to set the value of the label? Thanks!

jsFiddle Demo

Iterate through the label elements looking for the property for="idname" like this:

var labels = document.getElementsByTagName("label");
for( var i = 0; i < labels.length; i++ ){
 if( labels[i].outerHTML.indexOf('for="idname"') > -1){
  var UseLabelValue = labels[i].innerHTML;
  labels[i].innerHTML = "Replace Value";
 }
}
<label for="idname">Value here...</label>


<script>
document.getElementsByTagName('label')[0].innerHTML='new value';
</script>

https://developer.mozilla.org/ru/docs/DOM/element.innerHTML

http://javascript.info/tutorial/searching-elements-dom

A label has no value. If you want to set the text, you may use

element.innerHTML = "some text";

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