Alko
Alko

Reputation: 1439

jQuery, select element with exact class match

Is it possible to select exact matching class element like:

<i class="icon user"></i>
<i class="icon user add"></i>
<i class="icon user remove"></i>

so if I want to target

$("i.icon.user");

but the problem is all three elements are selected, since they all have common classes "icon" and "user"

I cant use :not() in this case to exclude classes, since this will be a dynamic selection, and I will not know ahead.

Upvotes: 0

Views: 1174

Answers (2)

Narendra Sharma
Narendra Sharma

Reputation: 116

If you want to select the specific class you can do in jQuery by using the selector.

Just use like if you want select add class:

$('i.icon.user.add').text();

this will give you what you want depends upon your requirements

 var add = $('i.icon.user.add').text()
 alert(add)

JSfiddle is here!

Upvotes: 1

Taplar
Taplar

Reputation: 24965

I would highly suggest that you give the element you want to target another class.

<i class="icon user theUser"></i>

Or something and target that extra class. There are various reasons for this. First off, to do an exact match, you are going to have to make some assumptions.

1) Potentially positional based: You could check to see if the class matches "icon user" exactly, but then if there is ever the case that the classes are flipped, it would not find it. fragile

2) Number of classes: You could check that the elements only have two classes, but if there is ever a case later that a third class is added then this would also break. fragile

By simply added a third class to this element to distinguish it from the other two, you avoid the need to filter the elements completely and you can target just the single element you want.

Upvotes: 0

Related Questions