JQuery - with a click of a link, copy all classes from one element to another

(see jsfiddle example)

When I clicked .link_to_rule_them_all, I would like to copy all the classes .link_to_rule_them_all span to #box and clear the β€œ#box” between each click.

my sample code and explanation is here http://jsfiddle.net/znCmq/2/

As you can see, I have no idea about js of this .. any ideas? eh ..

+4
source share
3 answers
$('.link_to_rule_them_all').bind('click', function(e) { e.preventDefault(); $('#box').attr('class', ($('span', $(this)).attr('class'))); }); 

living example: http://jsfiddle.net/moeishaa/3t33d/

+11
source

Use this:

 <a class="link_to_rule_them_all" href="javascript://"> $('.link_to_rule_them_all').click(function() { $('#box').attr('class',$(this).attr('class')) }) 

Native form for using a null href instead of a hash.

+2
source

First of all, you can add a listener directly to the span as follows:

 $('span').click(function(e) { 

Then you can add the class attribute to the DIV

 $('#box').append($(e.target).attr('class')); 

Ok let's try this then

 $('.link_to_rule_them_all').click(function(e) { //if you wanna attribute the span classes to the #box as classes var box = $('#box') box.removeClass(); box.addClass($(this).children('span').attr('class')); }) 

If you want to add the span class as TEXT:

 $('.link_to_rule_them_all').click(function(e) { var box = $('#box'); box.text(); box.append($(this).children('span').attr('class')); )} 
+2
source

Source: https://habr.com/ru/post/1345621/


All Articles