Anghel Gabriel
Anghel Gabriel

Reputation: 55

Jquery add class in a variable containig html string

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

Answers (4)

Ari
Ari

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

Mandeep Jain
Mandeep Jain

Reputation: 2664

You can do it in three ways:

  1. You let your HTMl markup execute first so that you can get as an DOM element and manipulate it.
  2. The hard and ugly way, treat the markup as a string and manipulate the string using 'substring' and/or 'slice'.
  3. 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

drmonkeyninja
drmonkeyninja

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

A. Wolff
A. Wolff

Reputation: 74420

var someVar = $('<i class="firstClass"></i>'); //embedded string in jquery object
someVar.addClass('secondClass');

Upvotes: 2

Related Questions