forX
forX

Reputation: 2153

jquery element same class

I search a simple/clean way to get every element with the same classes than a selected element.

something like that (not working)

var myElement = $("#elementId");

var listSameClass = $.hasClass(myElement.attr("class"));

Upvotes: 2

Views: 301

Answers (3)

Matt Ball
Matt Ball

Reputation: 359786

Yes, this is very simple:

var myElement = $("#elementId");
var classes = myElement.prop('class').split(/\s+/);
var classSelector = '.' + classes.join('.');
var otherElements = $(classSelector);

Demo: http://jsfiddle.net/mattball/58uQh


Not small enough? Let's make it into an unreadable one-liner!

var myElement = $("#elementId");
var otherElements = $('.' + myElement.prop('class').replace(/\s+/g, '.'));

http://jsfiddle.net/mattball/PQ5fX/

Upvotes: 4

isherwood
isherwood

Reputation: 61063

var myElClass = $(this).attr('class');
var $myEls = $(myEl).find(myElClass);

http://api.jquery.com/find/

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

I'd suggest, if I understand properly:

var currentClass = this.className,
    allWithClass = $('.' + className);

This does assume that a single class is present, however.

For elements with multiple classes:

var classes = this.className.split(/\s+/).join('.'),
    allWithClass = $('.' + classes);

Somehow I'd not realised that you were selecting an element by its id first, in that situation I'd advise you use Matt's answer, since any correction would essentially turn my answer into a duplicate. Oops.

Upvotes: 2

Related Questions