Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Append To Dynamically Created Element

I am dynamically appending a div element to an existing div. But immediately following that, I need to append another div to the div I just created dynamically. But I can't seem to find the dynamically created div in order to append to it. I assume maybe the DOM isn't aware of that div yet since I just made it. How do I do this?

var serialModel = "Test Test";
$("#existingDiv").append("<div id = '" + serialModel + "'></div>");
$("#" + serialModel).append("<div>content here</div>")

The last line doesn't do anything. The second line produces the new div, but then I can't find it to append to it.

like image 394
jmease Avatar asked Dec 05 '12 15:12

jmease


People also ask

How to append dynamic value in jQuery?

jQuery append() Method The append() method will add elements one after the other. A new element is added at the end of the last element. This method is attached with the dynamically created DIV elements, which serves as a container.

How to add dynamically in jQuery?

To add CSS properties dynamically, we use css() method. The css() method is used to change style property of the selected element. Here we have created two elements inside body tag i.e. <h1> and <h3> elements. We apply CSS property on <body> tag and <h1> tag using css() method dynamically.

How to dynamically create HTML element in jQuery?

You can use jQuery DOM manipulation methods like append(), appendTo() or html() to add new HTML elements like div, paragraph, headings, image into DOM without reloading the page again. In this tutorial, I will show you how to dynamically create a div and add that into a page by using pure jQuery.

Which one of the given option is used to add new element dynamically?

New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.


1 Answers

What if you do it vice versa:

$("<div />", { id : serialModel })     // create `<div>` with `serialModel` as ID
    .append("<div>content here</div>") // append new `<div>` to it
    .appendTo("#existingDiv");         // append all to `#existingDiv`
like image 168
VisioN Avatar answered Oct 13 '22 17:10

VisioN