What is the difference between:
document.getElementById("#grp").appendChild(grup).
and
this.grp.appendChild(grup);
Well, the first will fail, because you don't have any element with the id
"#grp"
(you dont' use the #
, that's the CSS expression for "the next thing is an id
"). With document.getElementById
, you don't put in the #
because it's just expecting an id
, not a CSS selector, so:
document.getElementById("grp").appendChild(grup);
About this
: this
will be determined by how generateDiv
is called. If it's called as an event handler on the grp
div
, then this
will (probably) already refer to the grp
element and you don't have to look it up again. If it's called some other way, then this
is probably something else, and you need to go look up the grp
div
via getElementById
.
Edit: From your code you posted later:
<asp:LinkButton ID="LinkButton1" OnClientClick="generateDiv(); return false;" runat="server" Text="Create New Group" CausesValidation="False"></asp:LinkButton>
...generateDiv
will see this
as the global object, and so you have to use document.getElementById
.
Side note: You can, and should, use the reflected properties for both the class
and id
attributes:
function generateDiv() {
var grup = document.createElement('div');
grup.className = 'genDiv';
grup.id = 'genId';
document.getElementById("grp").appendChild(grup);
}
...not least because IE8 (I think, could be IE7) and below get the class
one wrong if you use setAttribute
.