Da Artagnan
Da Artagnan

Reputation: 1199

Prepending template to img inside div

I need to dynamically put template above static img, which is located in div. To be more precised after I run function template(){} twice I want my HTML code to be like this one:

   <div class="main">
           <div id="templateID"></div>
           <div id="templateID"></div>
           <img src="~/Content/img/preload.gif" id="gifLoad"/>
    </div>

Before run my HTML looks like this:

  <div class="main">
    <img src="~/Content/img/preload.gif" id="gifLoad"/>
</div>

After running function template(){} twice my HTML looks like this:

<div class="main">
  <img src="~/Content/img/preload.gif" id="gifLoad"/> 
  <div id="templateID"></div>
  <div id="templateID"></div>
</div>

The function which suppose to add a template above img looks like this.

function template(data) {
        var parent = $('.main');

        var template = '<div id="templateID"></div>';

        var parent2 = $('#gifLoad');
        $('template').prependTo(parent2);

        parent.append(template);

    })

}

Can You help me out please?

Upvotes: 0

Views: 57

Answers (3)

Oleksandr T.
Oleksandr T.

Reputation: 77482

Use $.prepend instead of $.append, also id must be unique (<div id="templateID"></div>), change it to class

function template(data) {
    var parent = $('.main');
    var template = '<div class="templateID"></div>';
    
    parent.prepend(template);
}

template();
template();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
    <img src="~/Content/img/preload.gif" id="gifLoad"/>
</div>

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25527

You can use .append

var parent = $('.main');
var template = '<div class="templateID"></div>';
parent.prepend(template.clone());
parent.prepend(template);

OR use .before()

var template = '<div class="templateID"></div>';
$("#gifLoad").before(template);
$("#gifLoad").before(template.clone());

*Should not use duplicate ids. Use class instead of it.

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

The issue is:

  • .append() appends the data, to the end of the element.
  • .prepend() prepends the data, to the start of the element.

Use .prepend() instead of .append():

parent.prepend(template);

And also, it is not a good idea to duplicate ids, as they are meant to be unique. It is better to change the ElementID before prepending the data.

Upvotes: 1

Related Questions