简体   繁体   中英

How to add a span tag to a variable inside a .html Jquery method?

I'm having a difficult time finding out why this code doesn't work. Specifically, why I can't span the variable, and then add to it a class? Of course, I succeed in adding the class if it's just text, and not a variable.:

var fruit = 'bananas';
var paragraph = $('<div></div>');

paragraph.html('I like ' + '<span class="features">'fruit'</span>');
$(".features").css("color","yellow");

A few things I can see that is wrong with your code.

// fruit var is fine
var fruit = 'bananas';

// originally you had html markup in here, but you have to use html selectors.
var paragraph = $('div');

// you were close here but you didnt have plus symbols either side of your fruit var
paragraph.html('I like '+'<span class="features">'+fruit+'</span>');

// add the colour to your .features span - this is fine
$(".features").css("color","yellow");

See working fiddle here. https://jsfiddle.net/joshmoto/k0vrs8ne/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM