简体   繁体   中英

How to select all elements in class, including dynamically created elements?

I have some elements with the class "qss". I would like to go through them via a loop and change their text as per an array. It's all working fine, except if there are some qss elements that were added dynamically by JQuery (via.clone), those qss elements aren't picked up by this function. How can I go through all qss elements regardless of whether they are dynamically added?

This is my current code:

i = 0
$('body').find('.qss').each(function(){
  $(this).text(big_array[i]);
  i++;
});

There are two possibilities, either with a simple for loop with a better performance, or with the each() function and using the index parameter .

 var beforeArray = ['before 01', 'before 02', 'before 03'], bigArray = ['after 01', 'after 02', 'after 03']; // create dynamic elements var beforeArrayLength = beforeArray.length; for (var i = 0; i < beforeArrayLength; i++) { $('body').append( $('<p></p>').addClass('qss').text(beforeArray[i]) ); } setTimeout(function() { // first possibility with better performance // but you have to put it in a function where $qss is always newly set var $qss = $('body').find('.qss'), qssLength = $qss.length; for (var i = 0; i < qssLength; i++) { $qss[i].innerHTML = bigArray[i]; } // second possibility $('body').find('.qss').each(function(index, element) { $(element).text(bigArray[index]); }); }, 2000);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

You have to try using each() like this

$('.qss').each(function(i, obj) {
    //you can use this to access the current item
});

where 'i' is the postion in the array and obj is the DOM object that you are iterating (can be accessed through the jQuery wrapper $(this) as well).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM