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

如何使用jQuery在指定data-category-id的<tr>前添加新<tr>元素?

Yes, you absolutely can do this with jQuery!

jQuery makes inserting elements before a target element straightforward, and using the data-category-id attribute is the perfect way to pinpoint exactly where you want to add your new <tr>.

Here's how to implement this:

Basic Example (Insert HTML String)

You can directly pass an HTML string to the before() method to quickly insert your new row:

// Target the specific <tr> using its data attribute
const targetRow = $('tr[data-category-id="14"]');

// Insert a new <tr> immediately before it
targetRow.before('<tr><td colspan="100">This is the new row added before category 14</td></tr>');

Dynamic Element Creation (For More Control)

If you need to build the new row programmatically (e.g., adding custom classes, event listeners, or dynamic content), create the element with jQuery first:

// Build the new row and its content
const newRow = $('<tr>').addClass('custom-new-row');
const newCell = $('<td>').text('Dynamically generated row content').appendTo(newRow);

// Insert it before the target row
$('tr[data-category-id="14"]').before(newRow);

Handling Multiple Matching Rows

If there are multiple <tr> elements with data-category-id="14", the above code will insert the new row before each matching row. To target only the first occurrence, use:

// Option 1: Use .first() method
$('tr[data-category-id="14"]').first().before('<tr>...</tr>');

// Option 2: Use :first selector
$('tr[data-category-id="14"]:first').before('<tr>...</tr>');

The core idea here is using jQuery's attribute selector ([data-category-id="14"]) to precisely target the row you want, then using the before() method to insert your new element right where you need it.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:42:35