How do I select a newly added element in jquery?

I want to select a newly created item by doing something like this:

$("body").append("<div id='popup.dialog'></div>");
dialogDiv = $("#popup.dialog");

      

But after doing this the dialogDiv contains nothing. So is there a way to select the new createn item?

+2


source to share


4 answers


Period is not valid in ID. #popup.dialog

performs a search <div id='popup' class='dialog'>

. You have to replace it with a dash, for example



$("body").append("<div id='popup-dialog'></div>");
dialogDiv = $("#popup-dialog");

      

+1


source


Two things:

1) Don't use periods in your IDs

2) you could do it somehow better:



var dialogDiv =$('<div id="popup-dialog"></div>').appendTo('body');

      

At this point, you can chain more or just use a variable dialogDiv

.

This stops you from hitting your performance by selecting an item that you already have access to.

+2


source


I think your problem is the .

id.

The reason is that jQuery used .

to match the classes, which is why you are looking for an element with id = popup and class = dialog

0


source


You cannot have .

an id.

Try the following:

$("body").append("<div id='popup-dialog'></div>");
dialogDiv = $("#popup-dialog");

      

0


source







All Articles