Daniel Dropik
Daniel Dropik

Reputation: 783

In JQuery, .html(var) vs .html(var.html())

This code is provided for context, please see below for my question:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Document</title>
<script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $("document").ready(function() {

        var newItem = $("<p>This is a new paragraph</p>");
        $("#para2").html(newItem.html());
    });
</script>
<style type="text/css">
.a { color: Navy; }
.b { color: Maroon; }
</style>
</head>
<body>
    <ul id="list1">
        <li class="a">item 1</li>
        <li class="a">item 2</li>
        <li class="b">item 3</li>
        <li class="b">item 4</li>
    </ul>
<p class="a">This is paragraph 1</p>
<p id="para2">This is paragraph 2</p>
<p class="b">This is paragraph 3</p>
<p>This is paragraph 4</p>
</body>
</html>`

The is the part I am interested in:

var newItem = $("<p>This is a new paragraph</p>");
    $("#para2").html(newItem.html());

It appears to be functionally equivalent to this:

var newItem = $("<p>This is a new paragraph</p>");
    $("#para2").html(newItem);

The former method, I noticed in a video demonstration that teaches jQuery. As far as I know all that the added .html() part does is to get the matching element. To me, it doesn't seem like getting it in this case would help, since in var newItem = $("<p>This is a new paragraph</p>"); the $() already made it a Jquery object.


Question:

Is there a meaningful and impactful difference between the two above methods, or is it just a matter of coding preference?

Upvotes: 0

Views: 406

Answers (1)

Quentin
Quentin

Reputation: 943650

html() serialises the HTML inside the element to a string.

In this case, the difference is that $("#para2").html(newItem.html()); will give you some text and $("#para2").html(newItem); will give you a paragraph containing that text.

Since #para2 is a paragraph, and HTML does not allow paragraphs to be nested, the latter would also generate invalid HTML.


If you weren't creating the paragraph from scratch at at the same time (e.g. if var newItem = $("#existingParagraph");), then you would also be moving the element rather than copying its content.


Since you are just changing the text in the element, there is no need to create a jQuery object in the first place.

This:

    var newItem = $("<p>This is a new paragraph</p>");
    $("#para2").html(newItem.html());

is equivalent to:

    $("#para2").html("This is a new paragraph");

Upvotes: 3

Related Questions