J. Doe J. Doe - 2 years ago 65
jQuery Question

Where are dynamically created elements stored and how to access them? jQuery

I never really understood what's happening behind the behavior of dynamically created elements. Here's an example:

$('.some-list').append('<div class="node"></div>');

Where is that stored now? How can I access the div element $('.node')?

I know jQuerys 'on' method for events, but how do I simply access and manipulate that element? Thanks.

Answer Source

Whether $('.some-list') is itself present in the document, or not, you could simply use:

  // append returns the original collection ("$('.some-ist')"),
  // not the newly-added element(s)
  .append('<div class="node"></div>')
  // so here we can use "find('.node')" to find the newly added
  // element(s):

In the event of the $('.some-list') being present in the document already:

$('.some-list').append('<div class="node">The newly-added Element</div>').find('.node').css('color', '#f90');
.some-list div {
  color: #000;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="some-list">
  <div>Existing node</div>

In the event of the $('.node') element not being present in the document:

var someList = $('<div />', {
    'class': 'some-list',
    'html': '<div>Existing element</div>'
  newNode = someList.append('<div class="node">The newly-added Element</div>').find('.node');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download