I'm recieving a string (it may be either plain text or HTML text) from server, and I need to insert it into a div after that.
I can use $div.text(textFromServer)
if I know that textFromServer
is plain text.
If I know that textFromServer
is html I can do something like $(textFromServer).appendTo($div)
.
The problem is that I don't know for sure whether textFromServer
is plain or HTML.
So here's the question: is there a elegant and simple solution for my problem? Or do I have to analyse textFromServer
?
I'm recieving a string (it may be either plain text or HTML text) from server, and I need to insert it into a div after that.
I can use $div.text(textFromServer)
if I know that textFromServer
is plain text.
If I know that textFromServer
is html I can do something like $(textFromServer).appendTo($div)
.
The problem is that I don't know for sure whether textFromServer
is plain or HTML.
So here's the question: is there a elegant and simple solution for my problem? Or do I have to analyse textFromServer
?
-
Cant you just assume that the text is html and then do
$div.html(textFromServer)
? Even if it is plain text, it will get added fine. – Ravi Y Commented Dec 19, 2012 at 9:26 - Just append is OK, I think? – nhahtdh Commented Dec 19, 2012 at 9:26
- Check content-type of response ing from server, for 'text/plain' or 'text/html', based on that you can use .html() or .text() – Ranganadh Paramkusam Commented Dec 19, 2012 at 9:30
3 Answers
Reset to default 7Simply use html()
:
$div.html(textFromServer);
You're describing jquery.html().
$div.html(textFromServer)
should do the trick.
If there in no particular reason for knowing about data type (text / html) then you can directly assign the text / html to your div using [html()][1]
function like
$div.html(textFromServer)
If you are interested in knowing the type of data text / html
then you can store the type of your data (text, html) in hidden
field on server
and access that in javascript / jQuery
.