質問

I did a bit of Googling, and I found that the following code does not work because inputs[i].className is not a string. How would I make this a string??? I tried toString(). Also, inputs.length is not 0. I checked.

for (var i = 0; i < inputs.length; i++)
{
     if (inputs[i].className.indexOf("blah") == 1)
     {
      //do something
     }
}

I want to do something with only the inputs array values that have a class name of something like "blah 1;2;3;4".

Any help would be appreciated.

役に立ちましたか?

解決

indexOf(value) returns -1 when no match, and a index starting with 0 when there is match.

In your case, you should compare the result with 0, instead of 1.


Note that, if you want to test if a node has some certain class name, this is not a good practice.

A better approach is to use DOM API node.classList.contains() which is available in modern browsers.

Or use regular expression /\bblah\b/.test(node.className) to avoid the cases that blah is a substring of another class name, say not-blah.

Another way is to use mootools, which provides node.hasClass() to HTMLElement instances.

Or use jQuery like $(node).hasClass().

他のヒント

If you want to check if a class is present, check that indexOf() !== -1 as indexOf returns the index at which the searched for term begins. Checking for 1 would only work if it began at the second character. Similarly, checking for 0 will only work if it begins at the start, but if there is more than one class, it could appear at any number of other indices, in which case it would return some value other than 0.

As xiaoyi points out, you could have class names that are similar enough to the class name you're looking for that it could return false positives. To avoid that, if you still wanted to use indexOf, you would need to do some additional checking. First, I would split the className on ' ' and iterate through the resulting array doing the index check. Then, on any indexOf() !== -1 values, check that the length of the value is equal to the length of the value you're checking against.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top