In this simple tutorial you will learn how to copy class or id attribute from one element and apply it to another html element using jQuery, useful when you have some styles in a class and you can't edit the html source to clone it to the other element you need.
Supposing that you have a div with 2 class names and another div with a single class name. You want to duplicate the 2 classes to the element with that single class. Here is a sample of what I want to explain you:
<div class="firstClass secondClass">Div 1</div> <div class="differentClass">Div 2</div>
And the expected results should be with the desired element containing all classes:
<div class="differentClass firstClass secondClass">Div 2</div>
In this example we will try to copy all classes, using jQuery addClass() function, from a certain element and add them to another element to contain all classes together, in our case using the structure above, to clone the 2 classes from Div 1 to Div 2.
$('.differentClass').addClass( $('.firstClass').attr('class') );
And the results are:
var getClasses = $('.firstClass').attr('class'); var splitClasses = getClasses.split(' '); $('.differentClass').addClass( splitClasses );
The first variable getClasses is used to store all classes. It will contain a single string "firstClass secondClass" which will used in a second variable splitClasses to split the string, whenever blank space is present, into an array. Results will be:
splitClasses => 'firstClass' splitClasses => 'secondClass'
Then you can output values for each array position, like I did above. First position of an array start with 0 (zero). To read more about how arrays works check this link.
This is another structure containing a <div> with id attribute and another <div> with 2 classes.
<div id="someId">Div 1</div> <div class="firstClass secondClass">Div 2</div>
To copy the id of an element and add it to another element, but inside the class attribute is basically the same thing.
$('.firstClass').addClass( $('#someId').attr('id') );
As there is not any jQuery function to add id like we do with classes, we need to use .attr() function to get the id attribute and apply it to another element.
$('.firstClass').attr( 'id', $('#someId').attr('id') );
This technique is useful when you don't have access to html source or you want a faster and dynamic solution to copy class or id from an element and add it to another. If this solution helped you, make sure to share it to help others. You can check the video tutorial to see a live example or if something is unclear for you.