限制从.find()返回的div数量

Noo*_*kie 2 javascript jquery

我目前正在从单个页面上的每篇文章中收集div,然后遍历它们以查找包含该类的所有div .so-widget-hello-world-widget.这工作正常,但我很难将其限制为只有5每篇文章.

我尝试过使用slice,limit并添加一个计数器,但似乎没有任何效果.

我有什么明显的遗失吗?

jQuery(function($) {
    $('article').each(function(index, obj){
        var product = $(this).find('.so-widget-hello-world-widget')
        $(this).append(product)
    });
});
Run Code Online (Sandbox Code Playgroud)

Jus*_*ode 5

使用lt选择器文档

$(this).find('.so-widget-hello-world-widget:lt(5)')
Run Code Online (Sandbox Code Playgroud)

$('article').each(function(index, obj) {
  var products = $(this).find('.so-widget-hello-world-widget:lt(5)');
  products.each(function(index, el) {
    $(el).css({
      background: 'red'
    });
  })
})
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
  <div class='so-widget-hello-world-widget'>div1</div>
  <div class='so-widget-hello-world-widget'>div2</div>
  <div class='so-widget-hello-world-widget'>div3</div>
  <div class='so-widget-hello-world-widget'>div4</div>
  <div class='so-widget-hello-world-widget'>div5</div>
  <div class='so-widget-hello-world-widget'>div6</div>
  <div class='so-widget-hello-world-widget'>div7</div>
  <div class='so-widget-hello-world-widget'>div8</div>
  <div class='so-widget-hello-world-widget'>div9</div>
  <div class='so-widget-hello-world-widget'>div10</div>
</article>
Run Code Online (Sandbox Code Playgroud)