You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将jQuery多元素选择结果转换为jQuery对象数组的方法

Simplifying Your jQuery Object Array Code

Hey there! Let me break down how to clean up that repetitive jQuery selector code you started with.

First, let's recap your original approach:

var rows = [ 
  $('#view-content > .row:nth-child(1) > .row-content'), 
  $('#view-content > .row:nth-child(2) > .row-content'), 
  $('#view-content > .row:nth-child(3) > .row-content'), 
  $('#view-content > .row:nth-child(4) > .row-content') 
];

You're totally right that this creates an array of jQuery objects—rows[0] gives you the first jQuery-wrapped element, and rows[0][0] pulls out the raw DOM node underneath. But this is pretty repetitive, so let's simplify it!

Option 1: Use a jQuery Collection (Most Common Approach)

jQuery natively returns a collection of matched elements when you use a selector that targets multiple items. You can rewrite your code in one line:

// Select all .row-content elements inside direct .row children of #view-content
var $rows = $('#view-content > .row > .row-content');

Here's how to work with this collection:

  • Get the nth element as a jQuery object: Use $rows.eq(0) (note: eq() uses 0-based indexing, so eq(0) matches your original :nth-child(1))
  • Get the raw DOM element: Use $rows[0] or $rows.get(0) (both work the same way)

If you only want the first 4 elements (matching your original code's :nth-child(1) to :nth-child(4)), add the :lt(4) selector to target items with an index less than 4:

var $firstFourRows = $('#view-content > .row:lt(4) > .row-content');

Option 2: Get a True Array of jQuery Objects

If you specifically need an array of individual jQuery objects (instead of the jQuery collection), use .map() to wrap each DOM element and .get() to convert the result to a plain array:

var rowsArray = $('#view-content > .row > .row-content').map(function() {
  return $(this);
}).get();

This gives you the exact same array structure as your original code, but without the repetitive selector writing.

Either way, you'll cut down on redundant code while keeping the functionality you need!

内容的提问来源于stack exchange,提问作者Swiffy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:55:34