简体   繁体   中英

How to use a CSS selector on a javascript list?

Why does this not work?

var animals = ['Cat', 'Dog'].valueOf;

if ("animals:contains(Cat)") {
    // ...
}

You want to use the indexOf method of Array :

if(animals.indexOf('Cat') != -1){
    // ...
}

Any string that isn't empty ( "" ) will be truthy , so the body of the if will always run if you do if("some string") .

You can't use a CSS selector on an array in Javascript. You can use indexOf to see if a particular string exists in the array.

if (animals.indexOf('Cat') > -1) {
  console.log('We have kitties.')
}

The only time you'd really use a CSS selector in Javascript is when you're querying the DOM.

It seems you want something like JSONSelect :

JSONSelect defines a language very similar in syntax and structure to CSS3 Selectors. JSONSelect expressions are patterns which can be matched against JSON documents.

Note that :contains is not a standard CSS psedo-class, but JSONSelect provides it as an extension.

 var animals = ['Cat', 'Dog']; if (JSONSelect.match(':contains("Cat")', animals).length) // truthy document.write('There is a cat'); if (JSONSelect.match(':contains("Elephant")', animals).length) // falsy document.write('There is an elephant');
 <script src="http://jsonselect.org/js/jsonselect.js"></script>

But of course, this is overkill. Better use approaches explained in How do I check if an array includes an object in JavaScript? .

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