开发者

How can I get the class name with contain 'map' in jquery?

Does anyone how can I get the class name with contain word 'map' with jquery? I'm using the following code to get the class name with map (eg. class="mapTe开发者_开发知识库st"), but it not work if the class contain 2 name (e.g class="abctest map test"). Does anyone know how can I fix it?

     $(":input[class^=map]").each(function(index, element) {
        map_array.push(this.className);
    });


Have you tried the contains selector? It checks the class name to see if it contains a specified substring. For example:

$('input[class*="map"]');

See if that works.

More here: http://api.jquery.com/attribute-contains-selector/


You were close, you want *=, not ^=:

$(':input[class*="map"]').each(function(index, element) {
    map_array.push(this.className);
});

This is the "attribute contains" selector (jQuery docs, CSS spec).


About the quotes: They're optional if the value you're searching for fits the definition of a CSS identifier (your map value does, for instance). They're required if you're matching something that doesn't fit that definition (like anything with a space in it, or starting with an unescaped digit).

Since quotes are never wrong, best to always use them, but you don't have to if you know you're looking for a simple thing like map.


Try using ~= instead. It checks for if it contains the text in cases of multiple classes.

$(":input[class~=map]").each(function(index, element) {
        map_array.push(this.className);
    });

Edit: Sorry, I should clarify. This is for matching when there are multiple classes. (If you had class="map blahmap") it would match map only, where-as *= would match both - This is more useful when you're trying to check if something has a specific class name amongst multiple classes)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜