Nickso
Nickso

Reputation: 805

How to modify values of a template html inside a variable

I have an Ajax call that gets different description, and url address of a video:

function TraerInstructivos() {
    $.ajax({
        type: "GET",
        url: '<%= Page.ResolveUrl("~/Instructivo/Instructivos.aspx") %>' + '/TraerInstructivos',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var res = JSON.parse(response.d);
            $.each(res, function (i, item) {
                DibujarVideo(item);
            });
        },
        error: function (response) {
            alert("Error");
        }
    });
};

Now DibujarVideo is the method that will grab the template I have in my ascx, make a copy and then append it. This is the HTML of the ascx:

<div id="Videos">

</div>

<template id="video-elem">
    <div class="row">
        <div class="col-lg-4">
            <font id="video-desc" size="3"></font>
            <br />
            <br />
            <p><a id="video-ref" class="btn btn-secondary" href="#" role="button">Mira el Video &raquo;</a></p>
        </div>
    </div>
    <br />
    <hr />
</template>

Right now, the method that copies the template html looks like this:

function DibujarVideo(video) {
    var elemACrear = $("#video-elem").html();

    $(elemACrear).find("#video-ref").attr("href", video.DireccionVideo);

    console.log(elemACrear);

    $("#Videos").append(elemACrear);

}

What I see in the console log, and the page is that the value of href is not changing, but If I save this in a variable I see the changes for example:

var elem = $(elemACrear).find("#video-ref").attr("href", video.DireccionVideo);

So I reckon is not the same changing/manipulating the DOM tree in a page vs in a variable.

How can I change that href inside my elemACrear variable?

Im learning jQuery, every help appreciated.

Upvotes: 3

Views: 1448

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337666

You've already diagnosed and solved the issue without following the logic through. You simply need to provide the jQuery object you create in the elem variable to the append() call, like this:

function DibujarVideo(video) {
  var elemACrear = $("#video-elem").html();
  var $elem = $(elemACrear);
  $elem.find("#video-ref").attr("href", video.DireccionVideo);
  $("#Videos").append($elem);
}

Upvotes: 2

Related Questions