Canna
Canna

Reputation: 3794

How can i append pure string into div?

So this is the requirement. The user can insert tags inside text_field input.

and i got the data from the db like this.

var input = "test<br/><iframe src='http://stackoverflow.com/'>" ;

I ONLY want to append this to PURE string. not tags

but if i append it runs like a tag.

the result i want is just printing

test<br/><iframe src='http://stackoverflow.com/'>

as a pure string.

Any good solution?

html,

<div id="i_want_only_string">

</div>

javascript,

$(function(){
            var input = "test<br/><iframe src='http://stackoverflow.com/'>" ;
            $("#i_want_only_string").append(input);
});

DEMO

Upvotes: 0

Views: 75

Answers (2)

tewathia
tewathia

Reputation: 7298

You can append your container with the contents of a new tag that has your input text as its innerText

$(function () {
    var input = "test<br/><iframe src='http://stackoverflow.com/'>";
    $("#i_want_only_string").append($('<span>').text(input).contents());
});

DEMO

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try appending a TextNode - create it using document.createTextNode()

$(function () {
    var input = "test<br/><iframe src='http://stackoverflow.com/'>";
    $("#i_want_only_string").append(document.createTextNode(input));
});

Demo: Fiddle


As @BillCriswell noted below if the container #i_want_only_string is empty, you can use .text() like

$(function () {
    var input = "test<br/><iframe src='http://stackoverflow.com/'>";
    $("#i_want_only_string").text(input);
});

Demo: Fiddle

Upvotes: 2

Related Questions