Search code examples
jquerydomelementinsertafter

jQuery insertAfter is not a function


I need to insert element to a Dom element outside for each:

$items1 = [];
$.each($('.qs-option-name'), function () {
   if($(this).find('span.highlighted').length === 1){
      $item  = $(this).parent().parent();
      console.log($item);
      $items1.push($item);
   }
 });
 console.log($items1);
 $items1.insertAfter('ul li.first');

console.log() inside for each: enter image description here

console.log() outside for each:

enter image description here

Not sure looping an array again to insert is efficient is there a way to insert an array of DOM elements in one go?


Solution

  • The issue is because $items1 is an array of jQuery objects and therefore does not have a insertAfter() method.

    To solve this you could create a jQuery object from the array:

    $($items1).insertAfter('ul li.first');
    

    Alternatively you can use add() to combine jQuery objects instead of creating a basic array:

    var $items1 = $();
    $('.qs-option-name').each(function() {
      if ($(this).find('span.highlighted').length === 1) {
        $item = $(this).parent().parent();
        $items1.add($item);
      }
    });
    $items1.insertAfter('ul li.first');
    

    However you can make the logic more succinct using :has() and map():

    var $items1 = $('.qs-option-name:has(span.highlighted)').map(function() {
      return $(this).parent().parent();
    }).get();
    $items1.insertAfter('ul li.first');
    

    Note that the above is slightly different in that :has() will match any child, not only a single instance as your original did, but given the context that doesn't seem an important distinction.