0

Why don't the two statements below accomplish the same thing?

$('li.list1').html(function() {
return '<em>' + $(this).text() + '</em>';
});

and:

$('li.list1').html('<em>' + $(this).text() + '</em>');
ray9209
  • 378
  • 2
  • 13
  • 1
    Should do some google and start from the api itself http://api.jquery.com/html/ – andrex Sep 21 '14 at 08:35
  • http://devdocs.io/jquery/html – hjpotter92 Sep 21 '14 at 08:37
  • The call to this method empties the selected element's contents before updating it. `$(this)` represents the current (emptied) element. – melancia Sep 21 '14 at 08:39
  • **function** _Type: Function( Integer index, htmlString oldhtml ) => htmlString_ A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. – melancia Sep 21 '14 at 08:39
  • "this" in this context is not what you mean – sdespont Sep 21 '14 at 08:49

1 Answers1

4

According to the documentation, the .html() callback when used to replace the selected element's content empties it before doing so.

If you use a function in the callback, you get two parameters back: The element's index and its current content (before emptied).

So, you could do this way:

$('li.list1').html(function (index, oldHtml) {
    return '<em>' + oldHtml+ '</em>';
});

Demo

jQuery .html(function)

$(function () {
  $('li.list1').html(function (index, data) {
      return '<em>' + data + '</em>';
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li class="list1">Text</li>
</ul>

This way won't work: $('li.list1').html('<em>' + $(this).text() + '</em>');

$(this) here refers to the jQuery object Window, unless it's within some kind of wrapper, like an event handler:

$('li.list1').on('click', function () {
    $(this).html('<em>' + $(this).text() + '</em>');
});

Demo

$(function () {
  $('li.list1').on('click', function () {
      $(this).html('<em>' + $(this).text() + '</em>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li class="list1">Text</li>
</ul>
melancia
  • 9,119
  • 2
  • 26
  • 45
  • What if $(this) is within a wrapper that's within another wrapper - which object would it refer to in that case? – ray9209 Sep 22 '14 at 23:54
  • If the wrapper is a callback method which returns the selected element, it will be itself. The way to make sure is to check the documentation. – melancia Sep 23 '14 at 04:54