jQuery – difference between html() and text()

Jquery can be used to set content on and element (div, etc.) using text() and html() methods. Methods text(content) will first convert the content using html entities and set in that element. Here is code snippet and its outcome to explain the difference.

Setting values using jQuery text() and html()

Code example to set value in div using text() and html():

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id=id1>id1</div>
<div id=id2>id2</div>
<script type="text/javascript">
  $(function() {
    $("#id1").html('id1: <a href="/">infoheap</a>');
    $("#id2").text('id2: <a href="/">infoheap</a>');
  });
</script>
refresh

Reading values using jQuery text() and html()

Code example to read value in div using text() and html():

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<div id=id3>hello <span>world</span></div>
<script type="text/javascript">
  $(function() {
    console.log($("#id3").text());
    console.log($("#id3").html());
  });
</script>

Here is the outcome (console log) from this code:

hello world
hello <span>world</span>
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments