0

I am inserting a div to another div and I did make it with help of this post Inserting a Div Into another Div?. Here is my code which works fine. This function is called by a element

<asp:LinkButton ID="LinkButton1" OnClientClick="generateDiv(); return false;
"runat="server" 
Text="Create New Group" CausesValidation="False"></asp:LinkButton>

function generateDiv() {
          var grup = document.createElement('div');
          grup.setAttribute('class', 'genDiv');
          grup.setAttribute('id', 'genId');
          this.grp.appendChild(grup);
   }

What is the difference between:

document.getElementById("#grp").appendChild(grup)

and

this.grp.appendChild(grup); 
Community
  • 1
  • 1
Sam
  • 925
  • 1
  • 12
  • 28

2 Answers2

1

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.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • That's quick nice info, thank you. I was wondering about this in previously asked question, but now it's fine. – Sam Apr 30 '13 at 07:37
-1

html

<div id="box"></div>

js

var e = $('<div></div>');
$('#box').append(e); 
Davor Mlinaric
  • 1,989
  • 1
  • 19
  • 26