最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery getselect element by property value - Stack Overflow

programmeradmin1浏览0评论

Is there a way to get/select an element by it's property value, just as it is possible with the attribute values:

$('[attribute="value"]')

For example, I'd set a property using jQuery like this:

$('#foo').prop('my-property', 'value');

and then I'd like to find an element which has property 'my-property' and it has value 'value'.

Is there a way to get/select an element by it's property value, just as it is possible with the attribute values:

$('[attribute="value"]')

For example, I'd set a property using jQuery like this:

$('#foo').prop('my-property', 'value');

and then I'd like to find an element which has property 'my-property' and it has value 'value'.

Share Improve this question edited Jul 26, 2016 at 16:57 Silver Ringvee asked Jul 26, 2016 at 16:50 Silver RingveeSilver Ringvee 5,5356 gold badges32 silver badges48 bronze badges 3
  • Any particular property? – T.J. Crowder Commented Jul 26, 2016 at 16:53
  • Do you mean like an Input value? – Zeph Commented Jul 26, 2016 at 16:54
  • Any particular element? – MCMXCII Commented Jul 26, 2016 at 16:55
Add a comment  | 

1 Answer 1

Reset to default 20

No, there isn't anything exposed at the selector level that can select by property value, just (as you know) attribute value.

Some properties are reflections of attributes, which means that setting the property sets the attribute, which allows you to use attribute selectors. For instance, an input element's defaultValue property is a reflection of its value attribute (which its value property is not).

Otherwise, you select by what you can and use filter to filter the resulting list to only the elements you actually want.

Re your edit:

For example, I'd set a property using jQuery like this:

$('#foo').prop('my-property', 'value');

No, there's no way to select by that property directly, you'd need something like my filter suggestion above:

var list = $("something-that-gets-you-close").filter(function() {
    return this["my-property"] == "value";
});

You might consider using data-* attributes instead:

$("#foo").attr("data-my-property", "value");

then

var list = $("[data-my-property='value']");

to select it (the inner quotes are optional for values matching the definition of a CSS identifier). Note that attribute values are always strings.

Beware: There's a persistent misconception that jQuery's data function is a simple accessor for data-* attributes. It is not. It manages a data cache associated with the element by jQuery, which is initialized from data-* attributes but disconnected from them. In particular, .data("my-property", "value") would not let you find that later via a [data-my-property=value] selector.

发布评论

评论列表(0)

  1. 暂无评论