Michael Benneton
Michael Benneton

Reputation: 325

JQuery CSS on html() text

var data = $("span", this).html(); /*grab all */
$calPopup.stop().fadeTo(300,1);
$calPopup.html(data);

I want to do something like:

data.css("font-size","10pt");

But if I do that, the html text doesn't even appear. Chrome's inspector says this:

Uncaught TypeError: Object *** has no method 'css' 

How can I apply a CSS modification to the text?

Upvotes: 0

Views: 2482

Answers (6)

Anthony Grist
Anthony Grist

Reputation: 38345

The .html() jQuery function returns a String, not a jQuery object, so there's no .css() function to use. However, if you want to apply that CSS style to all of those <span> elements, it's as simple as calling your .css() function directly on the jQuery object that's selected them:

$('span', this).css('font-size', '10pt');

Note that I've removed the variable declaration because, based on the code provided, it seems unnecessary. Also note that the .html() function will return the HTML of the first matched element only, not all of them, so if you have more than one <span> element then you'll only get the HTML of the first.

To address edits to the question:

var data = $("span", this).clone().css('font-size', '10pt');
$calPopup.stop().fadeTo(300,1);
$calPopup.empty().append(data);

Upvotes: 5

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

you're applying the css() method to the string returned by html() method and not to the element itself.

Do instead

var data = $("span", this).css("font-size","10pt").html();

or, even better, keep off style from javascript: just assign a class to your span element and let a css rule give the correct style

var data = $("span", this).addClass("yourclass").html();

CSS

.yourclass {
    font-size : 10pt;
}

Upvotes: 1

Murali Murugesan
Murali Murugesan

Reputation: 22619

The html() method will return the HTML text of the first matched element given in the selector. Here it returns just text and not jQuery Object

So better first find the jQuery Object and apply CSS

var data = $("span", this);
data.css("font-size","10pt");

Upvotes: 1

Chris Dixon
Chris Dixon

Reputation: 9167

You just need to apply your formatting to the actual span element. .html() is getting the HTML in a string format, so .css won't work.

If you want to do .css on the whole span, simply change your variable to var data = $("span", this);

Upvotes: 0

Dev
Dev

Reputation: 791

try wrapping data with $() to convert it to a jQuery object

$(data).css('font-size','10pt');

Upvotes: 0

gabitzish
gabitzish

Reputation: 9691

Don't apply the css on the html ... You have to apply it on the span :

var data = $("span", this).css("font-size","10pt").html(); /*grab all */

Upvotes: 0

Related Questions