Just wondering how I can use an element as the text of another element using jQuery.
Here is my code:
$("<a/>", {
"class": "test",
text: $("<span/>", {
"class": "label",
text: "My Label"
}),
click: function(){
console.log('clicked');
}
}).appendTo('#label_list');
Output:
<a class="test"></a>
Output when using .html() on span:
<a class="test">My Label</a>
Desired output:
<a class="test"><span class="label">My Label</span></a>
Setting the
textof an element is very different from setting thehtmlof an element.textis essentially the character data immediately contained by an element, exclusive of any nested tags. So trying to put html tags in thetextdoesn’t accomplish anything. You could sethtmlto nest a<span>within the<a>, but rather than setting eithertextorhtmldirectly as you are, the more jQuery-idiomatic way to accomplish what you want would be like this:Or if you insisted on using
html, you could do something like this:Edit: also, when you set
textorhtml, you need to set it as a string. Your example code isn’t doing anything because you are not using a string, you are using$(...), which is a non-string object (a jQuery object).Also, for more on the distinction between
textandhtml(and the fact that they have to be strings), see these pages of the jQuery docs: