Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery -- The right way to add a child element?

Tags:

jquery

This is my first day of jQuery, so bear with me. Currently, I am adding an element to my parent container by doing the following:

var uploadedContainer =$('#uploadedimages');
var uploadedItem = '<div><span>'+file.name
                 + '</span><span><a class="mylink" href=remove.aspx?img='
                 + safeUrl+'>Remove</a></span></div>';
uploadedContainer.append(uploadedItem);

While it works, I'm not sure if that's the right way to accomplish this task. Also, is it possible to add the element to the parent, and fade the child element in? An example of usage would be great!

like image 977
George Johnston Avatar asked Feb 03 '10 22:02

George Johnston


People also ask

How do you insert an element to your first child?

To insert element as a first child using jQuery, use the prepend() method. The prepend( content ) method prepends content to the inside of every matched element.

What is jQuery child method?

jQuery children() Method The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

How can add Li in UL dynamically using jQuery?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.


1 Answers

If you're going to be adding similar elements over and over, I would avoid using lengthy strings in your code. They are a pain to maintain, and create difficult-to-read code. I would instead encourage you to use a templating tool like Handlebars:

<script type="text/x-handlebars-template" id="tmpl">
    <div>
        <span>{{filename}}</span>
        <span><a href="remove.aspx?image={{safeUrl}}">Remove</a></span>
    </div>
</script>

Now we build a compiled template from the above:

var template = Handlebars.compile( $("#tmpl").html() );

All that is left now is to call the template function with our data object, append the resulting markup to our container (or body), and fade it in.

var data = { 
    filename: "foo.png", 
    safeUrl: encodeURIComponent("foo image")
};

$("body").append(template(data)).fadeIn();

The result is cleaner, more legible, code that will make sense and be easy to maintain.

Demo Online: http://plnkr.co/edit/7JVa2w6zOXdITlSfOOAv?p=preview

like image 94
Sampson Avatar answered Nov 13 '22 21:11

Sampson