Question

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>

Was it helpful?

Solution

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>');

OTHER TIPS

Try:

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

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

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>');

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top