Lac Viet
Lac Viet

Reputation: 720

Jquery end() method

I have a html file like this:

<!DOCTYPE HTML">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>

<ul id="a">
    <li>list</li>
</ul>
<ul id="b"></ul>

<script type="text/JavaScript" src="js/1.3.2/jquery.min.js"></script>

</body>
</html>

When I load this script:

alert(
    jQuery('ul#a li')
    .parent()
    .clone(true)
    .find('li')
    .appendTo('#b')
    .end()
    .end()
    .text();
)

It gives me a 1 empty lines. However if I do this:

alert(
    jQuery('ul#a li')
    .parent()
    .clone(true)
    .text();
)

It show me "list" on alert box. I expect the two above code is the same, so they should show the same result. Could you explain me why the difference occurred ?

Thank you.

Upvotes: 0

Views: 296

Answers (1)

Riaan Walters
Riaan Walters

Reputation: 2676

I changed your code slightly

Basicly put, you had 1 .end() to many, which pushed too many elements off the stack

     alert(
        jQuery('#a li')
        .parent()
        .clone(true)
        .find('li')
        .appendTo('#b')
        .end() // If you remove this it will give you the text of the newly added element
        .text() //else it will give you the text of the element you cloned
    )

Doing this, will give you the same as the above, without the end (Obviously not appending it anywhere - but the same text)

    alert(
        jQuery('#a li')
        .parent()
        .clone(true)
        .text()
    )

Upvotes: 0

Related Questions