0

I want to select elements which include appended new elements also after selecting. I can do it by document.getElementsByClassName. It includes new appended elements. Like that:

var div1 = $('<div />').addClass('new_div1');
$('body').append(div1)
var divs = document.getElementsByClassName('new_div1')
divs.length // 1
var div2 = $('<div />').addClass('new_div1');
$('body').append(div2)
divs.length // 2; here divs includes newly appended element

But I wanted to it with jQuery. I tried like this, but not working as I expected.

var div1 = $('<div />').addClass('new_div')
$('body').append(div1)
var divs = $('.new_div')
divs.length // 1
var div2 = $('<div />').addClass('new_div')
$('body').append(div2)
divs.length // 1; here I want to see 2 with newly appended element

How can I select elements like document.getElementsByClassName in jQuery?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Ikrom
  • 4,785
  • 5
  • 52
  • 76
  • Why do you want to do this with jQuery, when the underlying JavaScript gives you a live `nodeList` which does this automagically? – David Thomas May 29 '13 at 06:54
  • @DavidThomas You're right, but I need to use some jQuery methods on it. – Ikrom May 29 '13 at 06:56
  • why can't you run `divs = $('.new_div')` again – Arun P Johny May 29 '13 at 07:06
  • @ArunPJohny It is placed in `for` loop, that's why I didn't want to select each time. I think it's bad practice selecting DOM element in `for` loop. – Ikrom May 29 '13 at 07:13
  • jQuery return array like object with chainable feature . `getElementsByClassName` returns `HTMLCollection`. could u check this answer http://stackoverflow.com/questions/7754269/create-a-htmlcollection – rab May 29 '13 at 07:14
  • @bob it is valid only if the elements are constant, if they are dynamic there is no other way that running the query again. – Arun P Johny May 29 '13 at 08:05
  • Another solution is possible if the elements are added under your control in that case you can add the dynamically added elements back to the `divs` array using the [add()][http://api.jquery.com/add/] method. ex: `var dynamicels = $('').appendTo(''); divs.add(dynamicels ); – Arun P Johny May 29 '13 at 08:06

0 Answers0