UserDy
UserDy

Reputation: 357

jQuery: Dynamically add class that belongs to another element

I want to add a class to an element that belongs to the element that was just clicked. The class changes but they all begin with fa-.

So I want to dynamically get the class of the element that was just clicked, and add it to a different element. I tried this but for some odd reason it doesnt work.

$(".fa").on("click", function() {

    var Icon = $(".icon");

    Icon.addClass($(this).attr("class").match(/fa-[\w-]*\b/));

});

I even alerted this to make sure its getting the class and it is.

alert($(this).attr("class").match(/fa-[\w-]*\b/))

Upvotes: 1

Views: 93

Answers (2)

Alex Filatov
Alex Filatov

Reputation: 2321

$(".get-from-this").on("click", function() {

  var selectedOptionIcon = $("#add-to-this");
  selectedOptionIcon.addClass($(this).attr("class").match(/fa-[\w-]*\b/).toString());
});

Upvotes: 1

Scimonster
Scimonster

Reputation: 33399

match() returns a String object, not a primitive string; it needs to in order to add those extra properties to it. jQuery doesn't seem to like String objects; perhaps it tests via typeof ... == 'string', which returns false for a String object.

Simply adding +'' to force it to a string makes it work:

 selectedOptionIcon.addClass( $(this).attr("class").match(/fa-[\w-]*\b/)+'' );

Working fiddle.

Upvotes: 2

Related Questions