简体   繁体   中英

Strict Equality in JQuery '$' selector

I've a custom data attribute in the element that are rendered in the html

<div my-custom-attrib="1".../>
<div my-custom-sttrib="2".../>

Now in the JQuery I want to filter between the elements based on the custom attribute value for that I'm doing the JQuery code like this:

var value = GetValueOfCustomAttribWeDontNeed() //-> This function returns an Int Value
$('[my-custom-attrib !="'+value+'"]').foreach(...)

Here when I'm using this '!=' (or '==') then its working perfectly, but when i'm trying to use strict equality ('===' or '!=='), its throwing error saying the expression is unrecognized.

$('[my-custom-attrib!=="'+value+'"]').foreach(...)
Syntax error, unrecognized expression: [my-custom-attrib!=="2"]]

My question is: is it even possible to use strict equality in '$' selector like this or there is any other way, or can we only use normal equality operators in '$' selector?

jQuery selectors is based on CSS selectors. jQuery add some new pseudo selectors (like :input ) but it's still CSS syntax.

CSS attribute selectors does not support strict equality because in the CSS world everything is a string.

More information on CSS attribute selectors

No, you can't do it. Selector you use is CSS selector and its syntax for attribute selectors != has nothing to do with Javascript comparison operators. If you want to be able to use Javscript, you will need to select all elements with attribute [my-custom-attrib] and then filter necessary elements:

$('[my-custom-attrib]').filter(function () {
  return $(this).attr('my-custom-attrib') !== value
}).each(function () {
  // ...
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM