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

通过jQuery.data()添加数据后,如何获取对应的DOM元素?

How to Select Elements with Data Stored via jQuery’s .data() Method

Great question — this is a super common gotcha with jQuery’s .data() method, and I’ve tripped over it more than once myself!

As you noted, when you use $(element).data('key', value), jQuery doesn’t add or update a data-key attribute on the DOM element. Instead, it stores that data in an internal $.cache object, which is why your attribute selector $('.modal-body[data-id=4]') doesn’t work — there’s no actual data-id attribute to match.

Here are a few reliable ways to get those elements:

1. Use .filter() to Check Internal Data

The most straightforward approach is to use jQuery’s .filter() method to iterate over elements and check their stored data values:

function second() {
  var modal_body = $('.modal-body').filter(function() {
    // Check if this element's stored 'id' data matches 4
    return $(this).data('id') === 4;
  });
}

This works because .filter() runs a check against every element in the initial selection, and only keeps the ones that return true from the callback.

2. Sync Data with DOM Attributes (If You Need Attribute Selectors)

If you specifically want to use attribute selectors later, you can manually sync the data with a data-* attribute when setting it. Just chain .attr() alongside .data():

function first() {
  var modal_body = $('.modal-body');
  // Set internal data AND update the DOM attribute
  modal_body.data('id', 4).attr('data-id', 4);
}

Now your original attribute selector $('.modal-body[data-id=4]') will work. Just keep in mind: if you later update the data with .data('id', 5), the data-id attribute won’t automatically update — you’ll need to call .attr('data-id', 5) again to keep them in sync.

3. Store the Element Reference (Most Efficient)

If you’re working with the same element across multiple functions, skip re-selecting it entirely. Store the element reference in a shared scope (like a closure or module-level variable):

// Define a variable in a scope accessible to both functions
let cachedModalBody;

function first() {
  cachedModalBody = $('.modal-body');
  cachedModalBody.data('id', 4);
}

function second() {
  // Use the pre-stored element instead of re-querying the DOM
  console.log(cachedModalBody.data('id')); // Outputs 4
}

This is the most performant option because it avoids unnecessary DOM traversals.


内容的提问来源于stack exchange,提问作者Valentin Emil Cudelcu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:49:23