London
London

Reputation: 15274

Strange ie behaviour with jquery inArray

Hello this seems to be working on IE8 :

var clsName = link.parents("div.fixed_column").attr("class").split(" ");

if($.inArray("column_one", clsName)

While this one reports error (Object expected errror in jquery).

var clsName = link.parents("div.fixed_column").attr("class");

What is the right way to do this? I thought purpose of inArray was that jquery will handle cross browser issues.

Upvotes: 0

Views: 328

Answers (2)

Ian
Ian

Reputation: 50905

Unfortunately, this is indirectly answering your question, but... You seem to be looking to detect if an element has a class, and since you're already using jQuery, just use the hasClass method - http://api.jquery.com/hasClass/

For your specific code, try:

if (link.parents("div.fixed_column").hasClass("column_one")) {
    // It has the "column_one" class
}

The more immediate answer to your question is that link.parents("div.fixed_column").attr("class") returns a single string. When the jQuery selector (div.fixed_column) returns multiple elements, which is very possible when using classes, using jQuery methods that get information (like .attr, using one parameter...to "get" the value) return the first matched element's value only.

So say the selector matches 3 elements:

["<div id='div30' class='fixed_column div30_class'></div>",
 "<div id='div2' class='fixed_column div2_class'></div>",
 "<div id='div17' class='fixed_column div17_class'></div>"]

Then the value returned from .attr("class") will be: fixed_column div30_class because it's the first matched element.

I'm not sure, but I think you're expecting jQuery to return an array of all the matched elements' values, which it just doesn't. So that doesn't mean jQuery isn't handling cross-browser issues, it just means you need to look up what the method does/returns.

I could've sworn that jQuery 2.0 has options for doing what you want - directly from calling the getters (or something similar), but I can't find it anymore :( Maybe I'm remembering incorrectly. Anyways, you could easily use $.each and/or $.map to look at every matched element, but it depends on what you were really trying to do with it.

Upvotes: 4

bfavaretto
bfavaretto

Reputation: 71908

You can't read the attributes of multiple elements into an array with .attr("class"). But why don't you just target the desired class in the selector like this?

var cols = link.parents("div.fixed_column.column_one");

Then change your conditional to check for an empty set:

if(cols.length) { ...

Upvotes: 1

Related Questions