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!
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With