Reputation: 55
I have this variable and i want to add a class to it. I tryed this method, but this defenetly is not working
var someVar = '<i class="firstClass"></i>';// Html Markup to be used later.
someVar.addClass('secondClass');
I need a different method to adding a new class to the html markup.
Thanks
Upvotes: 5
Views: 12239
Reputation: 4969
When we need to get the html string from some DOM component we extracted from its parent, (eg: sortable helper), then we can convert that string to jquery object first.
example:
var thehtml = $(ui.helper).html();
thehtml = $(thehtml); // convert to jquery object
thehtml.addClass("yourClass"); // we can then assign new class
ui.helper.replaceWith(thehtml); // do something you want with it
In your case
var someVar = '<i class="firstClass"></i>'; // Html Markup to be used later.
someVar = $(someVar); // convert to jquery object
someVar.addClass('secondClass');
Upvotes: 3
Reputation: 2664
You can do it in three ways:
Break up the markup and keep it in an array of strings, say array[0] = i class=; array[1] = firstClass; array[2] = /i>;
(i m new to stackoverflow and hence dnt knw how to write HTML in the answer, but i hope u got what i m tryin to explain) Then you can add as many classes as you want by simply concatinating the classname to a array[1](array[1] += ' classname'). And when you actually want to use it, reform the whole markup by addind all the bits. It is still ugly, but you will atleast get what you want.
Upvotes: 1
Reputation: 8540
You can only use addClass on a HTML element so you need to set your variable to be a DOM element (e.g. $('<i>')
):-
var someVar = $('<i>', {'class': 'firstClass'});
someVa.addClass('secondClass');
Upvotes: 3
Reputation: 74420
var someVar = $('<i class="firstClass"></i>'); //embedded string in jquery object
someVar.addClass('secondClass');
Upvotes: 2