tirenweb
tirenweb

Reputation: 31709

jQuery: trying to add a class to an element that at the beginning is an string:

Im trying to add a class to an element that at the beginning is an string:

var foobar = '<div>hello</div>';
$(foobar).addClass('my_class');
$('body').append($(foobar));

JSFIDDLE

but the class name is not added..

Upvotes: 0

Views: 45

Answers (2)

Dennis van Schaik
Dennis van Schaik

Reputation: 474

.addClass only works on DOM elements. since foobar is a string, you should use the .replace function:

var foobar = foobar.replace("<div>", "<div class='my_class'>"); 
$('body').append($(foobar));

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

addClass() after appending the element. Like this:

$(foobar).appendTo('body').addClass('my_class');

Working Demo

Upvotes: 3

Related Questions