Reputation: 351
This is my HTML code:
<div id=demo1></div>
<button onclick=demo()>this is button</button>
}
and this is my JavaScript code:
function demo(){
demo1.innerHTML="this is good syntax";
}
and this is a link that show how its work perfect... Please check the link before you say that this syntax will not work.
https://codepen.io/navehazan/pen/QgEeOr
My question is why to ever use document.getElementById("demo1").innerHTML
when I can use just demo1.innerHTML
?
Upvotes: 0
Views: 349
Reputation: 81
This is a new syntax, and although it's working, it's better and safer to use
document.getElementById("demo1").innerHTML=
Upvotes: 0
Reputation: 12176
What you are looking is called 'named access'. Elements with 'name' or 'id' attributes are directly appended as property to the dom. You can even access the element by using window object window['demo1']. So it's possible to select element in this way if an element has an id or name that is unique in the document.
Caveat:
What if you have markup like this.
<div id=demo1></div>
<input name="demo1"/>
<button onclick=demo()>this is button</button>
The markup is valid because you don't have duplicate id's. But the way the named access works is it associates 'id' and 'name' together. So in this case you wont be able to select the element by named access, because 'demo1' will be associated with both 'div' and 'img' and it will return an array. In order to avoid this problem we use document.getElementById()
Named access : https://www.w3.org/TR/html5/browsers.html#named-access-on-the-window-object
Upvotes: 1
Reputation:
demo.innerHTML="some text"
wont work you need to define "demo" as a DOM first, check the line below
var demo = document.getElementById("demo")
Upvotes: 0