-2

Why does this not work?

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

if ("animals:contains(Cat)") {
    // ...
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Riba
  • 1
  • 2
  • javascript doesn't know anything about css. you need to use a javascript function, not a css selector. – Patrick Goley Apr 16 '16 at 22:19
  • 2
    What HTML are you using, and what result do you expect to get? As for your `if`, it looks like you'd want to use `if (animals.indexOf('cat') > -1)`, using [`Array.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf). The reason it doesn't work, though, is because that's not how you use JavaScript. – David Thomas Apr 16 '16 at 22:19

3 Answers3

0

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").

1j01
  • 3,714
  • 2
  • 29
  • 30
0

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.

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
0

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?.

Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Something like this. In other word, what I need is: If this contains that change CSS of another element – Riba Apr 17 '16 at 00:12