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>');
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>');
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>';
});
$(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>');
});
$(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>