Nick Ginanto
Nick Ginanto

Reputation: 32130

Converting element classes to a selector

using $(elem).attr("class") or elem.className return a space seperated list of class names

Is there a better way to turn this in to a selector than

"." + classNamesString.split(" ").join(".")

Example

<div class="a b c"></div>
<div class="a b c"></div>
<div class="a b c"></div>
<div class="a b c"></div>
<div class="a b d"></div>
<div class="a b c"></div>
<div class="a b c"></div>

$("a").click(function(){

  var classNames = $(this).attr("class");
  $("body").find( < use classNames > ).colorBlue();

});

I am trying to avoid tiny utility functions and searching for some jQueryesque way to do it, if possible

Upvotes: 2

Views: 79

Answers (5)

guest271314
guest271314

Reputation: 1

Try utilizing .filter()

$("div").click(function() {

  var classNames = $(this).attr("class");
  var _selector = $("body *").filter(function() {
    return this.className === classNames
  });
  _selector.css("color", "blue");

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a b c">abc</div>
<div class="a b c">abc</div>
<div class="a b c">abc</div>
<div class="a b c">abc</div>
<div class="a b c">abc</div>
<div class="a b c">abc</div>
<div class="d e f">def</div>
<div class="a b c">abc</div>

Upvotes: 0

Sudharsan S
Sudharsan S

Reputation: 15393

For example

html

<div class="hai bye hello">Text</div>

jquery be

$("." + $('div').attr('class').split(" ").join(", .")).click(function() {

   alert('hello') 
});

your context be

 $("body").find("." + $('div').attr('class').split(" ").join(", .")).css('color', 'blue');

Fiddle

Upvotes: 0

Tran IT
Tran IT

Reputation: 1

here if you can try:

var class_element = ($(element).attr("class")).split(" ").join(", ."); $(class_element).yourfunction();

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74420

You can use attribute selector if similar classes are always set in same order in HTML markup:

$("body").find( '[class="' + classNamesString + '"]' ).colorBlue();

Upvotes: 0

Scimonster
Scimonster

Reputation: 33399

You could simplify it a little by just replacing spaces with periods:

"." + classNamesString.replace(/ /g,".")

Upvotes: 2

Related Questions