Unable to set the value into Label dynamically
I have a label as shown
<label id="label1"></label>
I am trying to set the value in it using
document.getElementById('label1').text = "ddd";
And i also i tried using Prototype as
$('label1').text = date1;
开发者_如何学Go
But still its not working
document.getElementById("label1").innerText = "foobar"
or alternatively
document.getElementById("label1").innerHTML = "<b>fatfoo</b>";
Use the following
$('#label1').text(date1);
text is a method here.
Use the innerText or innerHTML property:
document.getElementById("label1").innerText="ddd";
Try .innerHTML, innerText, .textContent, .nodeValue
I have only seen .text in selects
(I need to stop commenting and answer instead...)
A label element is supposed to enclose a form control, e.g.
<label id="label1" for="firstName">First name:
<input type="text" name="firstName" id="firstName"></label>
If that is how you are using it, then you don't want to replace it's innerHTML, innerText or textContent as doing so will completely replace the content of the label (removing any elements within it). If you aren't using the label this way, you should be using some other element, probably a span.
While innerHTML is widely supported, it's only been standardised in HTML5, which is still a draft. However, you can usually assume support and setting it is pretty consistent across browsers. Getting the property has foibles and isn't very consistent if it's anything other than trivial markup (e.g. text and simple inline elements).
The innerText property is a Microsoft proprietary property that is supported by IE and some other browsers, it definitely should not be used without feature testing. Similarly, the W3C DOM 3 textContent property is not widely supported, but is generally supported by those browsers that don't support innerText (some support both).
It's pretty easy to do a feature test and select which one to use, such as:
if (typeof element.textContent == 'string') {
// use textContent property
} else if (typeof element.innerText == 'string') {
// use innerText property
}
where element is a reference to a DOM element node.
It's probably best to wrap the text you want to replace in a span element and replace the content of that, either using innerHTML or, if it contains a single text node, its firstChild.data
.
精彩评论