Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery clone element in html

Tags:

jquery

dom

clone

Here I am using jQuery ajax:

$.ajax({
    type: "GET",
    url: URL,
    data: { Mode: "POB1"},
    success: function (data) {
        var Html = $.trim($(data).find("#divpob").html());
        if (Html) {
            $(Html).find(".lblpob").text("UserName" + Username);
            $(".DivRprt").html(Html);
        }
    }
});

here value of lblpob didn't get change, but if i use .clone() like this

if (Html) {
    var Html2 = $(Html).clone(true);
    $(Html2).find(".lblpob").text("UserName" + Username);
    Html = Html2;
    $(".DivRprt").html(Html);
}

lblpob gets changed.

What difference .clone() is making here ?

like image 225
Buzz Avatar asked Aug 23 '26 18:08

Buzz


1 Answers

There's an issue with temporary DOM objects and html as string. I'll break it down line by line:

What your first code does:

    var Html = $.trim($(data).find("#divpob").html());

Both the call to .html() and to $.trim() makes sure your Html var holds a string, not a live DOM object.

    $(Html) ...

This turns the Html string into a new DOM object (that you don't assign into a var),

    ... .find(".lblpob").text("UserName" + Username);

and change this unnamed DOM object. Not your Html string.

    $(".DivRprt").html(Html);

But here you use the original Html string to change the html of DivRprt.

What your other code does:

    var Html2 = $(Html).clone(true);

After creating a new DOM object and cloning it, you assign it into Html2,

    $(Html2).find(".lblpob").text("UserName" + Username);

and here you manipulate it.

    Html = Html2;
    $(".DivRprt").html(Html);

So here you insert the manipulated DOM object into .DivRprt

My option:

You don't need the .clone(), just keep track of the first DOM object:

    if (Html) {
        var Html2 = $(Html)
        Html2.find(".lblpob").text("UserName" + Username);
        $(".DivRprt").html(Html2);
    }

Or:

Just don't convert the trimmed data back to string

    var Html = $(data).find("#divpob");
    if (Html.length) {
        Html.find(".lblpob").text("UserName" + Username);
        $(".DivRprt").html(Html);
    }
like image 84
Refael Ackermann Avatar answered Aug 25 '26 09:08

Refael Ackermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!