How to insert html text with text() function? [closed]

霸气de小男生 提交于 2019-12-20 07:49:37

问题


I need to change the content of an element which includes html.

I tried with this, but the html tags are printed

    $('#content-sections label').text('my text <span>a span element</span>');

This is printed as it:

my text <span>a span element</span>


回答1:


You have to use html() for this. For example:

$('#content-sections label').html('my text <span>a span element</span>');

Oh, and for better performances, use this instead:

$('#content-sections').find('label').html('my text <span>a span element</span>');



回答2:


Try:

$('#content-sections label').html('my text <span>a span element</span>');

But i'm confused with your "including html text using jquery"




回答3:


you have to set with html(value) function which sets the HTML contents of the first element in the set of matched elements.

  $('#content-sections label').html('my text <span>a span element</span>');



回答4:


Aurelio's answer solves your problem.

But if you need to put a whole structure of html nodes, it's better to use this way:

var span = $("<span />").text('a span element');
$('#content-sections label').text('my text').append(span);

The first line creates the span with its contents

And the second does 2 things, it first sets the text of the label, then adds the span created in the first line after that text.




回答5:


You have to use like the code below

$('#content-sections label').html('my text <span>a span element</span>');

jQuery.html() treats the string as HTML, jQuery.text() treats the content as text that is the reason its printing the span tag as well.



来源:https://stackoverflow.com/questions/17368579/how-to-insert-html-text-with-text-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!