Reputation: 67
UPDATE: I have double checked again my code. The problem with it is actually the placement of the function (which I didn't post it up here) and I have fixed it!
This is just a short summary of my code. But it just won't run even if I put the js after my label.
< script type = "text/javascript" >
document.getElementById('lblSport').innerHTML = 'Hello'; < /script>
<label class="lblSport" id="lblSport">asas</label>
Upvotes: 0
Views: 2770
Reputation: 11
The label is undefined in your case because your code is being called before the actual label exists on the page. Try adding your code inside a "document ready" function for this to work. The document ready function will fire when the document is ready (Once the document loaded all it's elements).
<script type = "text/javascript">
$(document).ready(function () {
document.getElementById('lblSport').innerHTML = 'Hello';
});
</script>
<label class="lblSport" id="lblSport">asas</label>
Upvotes: 1
Reputation: 130
Your open and closing script html tags contain unneeded space. It should look like this:
<script></script>
As well, according to HTML5:
The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.
http://www.w3.org/TR/html5/dom.html#the-id-attribute
While you can have the same name for class and ID, best practice would probably be to avoid using same names, mainly for readability.
Upvotes: 0
Reputation: 5674
see this fiddle: https://jsfiddle.net/wk63pov0/
<label id="demo" >(innerHTML).</label>
Js:
document.getElementById("demo").innerHTML = " changed!";
please post your full html.
Upvotes: 0
Reputation: 68433
Your code is fine, check this demo
window.onload = function(){
document.getElementById('lblSport').innerHTML = 'Hello';
};
just ensure that element is loaded to DOM before your change its innerHTML
Upvotes: 0
Reputation: 452
Delete The space before script tag and the end of the script tag and it will work.
<script> .... </script>
Upvotes: 1
Reputation: 180
You have to wait for the page to be loaded, remove space on script tags and haven't the same name for the class and id
window.onload = function(){
document.getElementById('lblSport').innerHTML = 'Hello';
}
<label class="lblSports" id="lblSport">asas</label>
Upvotes: 0