Today, we’re going to learn how to dynamically create and remove elements. The “appendTo()”, “size()”, and “remove()” methods will be reviewed. As always, feel free to ask any questions that you might have. Enjoy!



Day 5: Creating and Removing Elements

Download the Source Code


Comments

Leave a Comment
  1. Once again, a nice tutorial. A clear walkthrough of the basics. Thanks for this one…waiting for the rest :)

  2. WOW great tutorial, i have so much to learn with jQuery, but you explain things really well :)

  3. Jeffrey,
    Thanks so much for your great efforts on these tutorials. You are doing an outstanding job! This is now my favorite website. Thanks for sharing your knowledge with the community. Keep it up!!!

  4. It’s kind a really begginer tut so I LOVE IT!! ^^ everybody know that can figure out some meanings of the script but this, step by step, IT IS PERFECT!! thanks a lot :D

  5. Great mate. Again thanks for your great tuts. I have just a question. Can I add new menus in this way with different menu text?

  6. @Kaly - Depends on what you need to do. Remember - all of this is happening on the client side. As soon as you refresh the page, it will revert back to its original form.

  7. @Andres - Thanks! That’s sweet of you.

  8. Jeffrey,
    One again, Thanks for doing this for us. You are excellent at explaining stuff.
    keep em coming.

  9. Again, excellent. Roll on day 6 and beyond.

  10. Hi Jeffrey, I have created a popup login box. After clicking on the submit button the page refresh and the box vanishing every time. Is there any way to fix it . I want just on clicking a “X” mark the pop up will fade out not on page refresh. Please suggest….

    Thanks
    Kaly

  11. @Kaly - Once you click on an input button, the page will refresh. So yes, any jQuery events will be reset as well.

    You could consider validating the user with a jQuery AJAX call. That way, there won’t be a postback. We’ll get there in a couple of weeks.

    To simply close a popup by clicking “X”, you could do:

    $(’#x’).click(function() {
    $(this).parent(’div#loginBox’).fadeOut(’slow’);
    });

  12. Very good tutorials Jeffrey. Thank you so much. Keep them coming. I am falling in love with these tutorials and I can’t get enough.

  13. How to create a auto rotate featured section with image in WordPress? And it is also controlled by different buttons. For example: There will be an image, title and description to be displayed by default. It loads the second articles in 5 seconds, or user also have the buttons to select which to be displayed.

    Thanks!

  14. great! cant wait for the next one. how many will there be!? the possibilities seem endless, love this series so much!

  15. Nice tutorials.

    What is the point of using $(’a#add’) for selector when you can use just $(’#add’) ?
    It is ID after all.

  16. @Roman -

    Both of those will work. Sometimes, I find that it helps me remember what I’m referring to when I read the code after months.

  17. So i did notice 1 small thing:
    - If you remove an item that doesn’t exist (ie: remove list item when none are displayed) the i variable will then be set to a negative.
    - We may have to re-declare the i variable’s size instead if i–;

    Just a thought ;x

  18. i would normally feel dumb asking this, but you did say ABSOLUTE beginners!

    when you are ADDING, you use “” in selecting the tag.
    when you are REMOVING, you use simply “li”

    is this just a syntax thing we should memorize when selecting using first, last, etc?

    thanks for everything. i appreciate these so much, and looking at the comments, im not alone!

  19. sorry, got filtered. hope you know what i meant in the “ADDING” line above. the li is displayed as a full tag.

  20. Would it work to remove the i++ and i– statements and move the variable declaration into the add function? If so, is there any downside to doing it that way?

  21. @Larry

    When adding, the li tag is not being selected. What he is doing is actually writing what will be added to the list, in this case he needs to ad new li tags. You could replace that with anchor tags for example. In the remove part he is indeed selecting the li tags, more specifically the last list item.

    @Johhny

    I noticed the same thing. How could that be fixed? Maybe something like, if i<1 then i=1. I don’t think that works but could be something similar. Does anyone have a solution?

  22. Definitely learned something here, but I don’t see the relevance of this in the real world. Why would I want someone to be able to click something and add another list item or paragraph or div or whatever.

  23. Thanks again…. my regular Sunday night show :D

  24. Gravatar

    Gustavo Scanferla

    Hi! I’m watching all videos, thanks.

    Wouldn’t it be less code to work with if you remove the “+ 1″ after the “.size()”
    and
    move the “i++” before appending the “”?

    It worked here =)

    var i = $(’#listo li’).size();

    $(’a#add’).click(function() {
    i++;
    $(” + i + ”).appendTo(’#listo’);
    });

    Thank you again!

  25. Gravatar

    Gustavo Scanferla

    The “li” vanished from my code above, sorry.

  26. Hi, great tutorial, but you can improve the code in this example . Just put size function inside of click event like this :

    $(’a#add’).click(function() {
    var i = $(’li’).size() + 1;
    $(” + i + ”).appendTo(’ul’);

    });

    $(’a#remove’).click(function() {
    $(’li:last’).remove();

    });

    This allows you to remove i++ and i– micromanagement and solves problem when removing all list items (when you click on remove list item a few times, and then click on add list item you will get negative numbers)

  27. Jeffrey, thank you for the wonderful tutorials. :)

    I ran into one problem though: the first function for adding list items is working a bit strange for me. It adds a list item after every existing item. I solved it by using this: “appendTo(’li:last’)” but I don’t understand why it happens. :)

    Thanks again for sharing the knowledge. :D

  28. Hey wouldn’t be smarter to declare de var i into de $(’#add’).click function ?
    So you wouldn’t need the i++ and the i–;

  29. Ok sorry i haven’t seen Conker’s Comment !
    I swear xD

  30. man sorry for flooding but the tutorials are awesome and like it was already said you explain things very well !
    (Sorry for any english error ^^)

  31. Gravatar

    Stew.Pidbeatch

    When decrementing the li indexer wrap it in a conditional so you don’t go negative, like this:

    if(i>1){
    i–;
    }

    Otherwise (and some have noted), you might get a negative number when you add back to the ul.

    Also note: the Firebug console output breaks the samples if you try running it in IE.

  32. You should be able to make it even shorter:

    1) remove + 1 from var i line
    2) in the append line, just use ++i. This should increment the variable, and then get it’s value (as oposite to i++ which gets its value and then incerement)

    Thats all, 2 lines removed :)

  33. I keep getting the following error from FireBug:
    [ Begin Error ]

    console is undefined
    [Break on this error] console.log(i);

    [ End Error ]

    Any thoughts?

  34. @Nicholas - Yes. My guess is that you’re viewing the site in Internet Explorer. Correct?

    Console.log should be used with Firefox and Firebug. Remove the console.log() line and refresh your browser.

    Does it work now?

  35. Definitely not using internet explorer, I use only Firefox and am on a Mac. I have had/used firebug for a year or so now.

  36. The first four screencasts were better. The talking in this one is way to fast.

  37. Hi Jeffrey,Thanks a lot for your wonderful videos ..

    Im having same problem with “console.log()” as Nicholas mentioned, but im using Vista + Firefox +Firebug..and it keep telling me “Console is not defined”.

    any suggestions?

  38. Hi Jeffrey
    Thank you very much!!!!! you are the best

  39. awsome!!! Thx a lot :)

  40. Darnelle,

    I thought the same thing. I tried out the following and it works. My guess is the downside is it a slower approach since $(’li’).size() would be called each time add is clicked. However, relying on the state of var i to be correct is less elegant and dangerous (some bug elsewhere in the running javascript could mistakenly alter the var i variable). Correct me if I am wrong about this.

    $(function() {
    // var i = $(’li’).size() + 1;
    $(’a#add’).click(function() {
    var i = $(’li’).size() + 1;
    $(” + i + ”).appendTo(’ul’);
    // i++;
    });

    $(’a#remove’).click(function() {
    $(’li:last’).remove();
    // i–;

    });
    });

  41. So what can i use this for in a real project?

  42. Hey there!

    great videos…

    i’d also place i = $(’li’).size + 1 inside the add function and avoid all the i++ and i– ? i find this easier to read and understand…

  43. this video stops at 00:37, and no longer plays…sad that i missed it…

  44. Gravatar

    Mickey Hoang

    thanks a lot

  45. Really good!
    I directly started using jQuery without HTML knowledge!

    Great!

  46. Hi mate cheers for these tutorials they’re awesome! I’m from NZ so you’re helping people all over the world :)

  47. first of all, thanks for the great tuts here…
    my question:
    would that example work with a little specification inside a textarea?
    like:

    ->put
    ->write text
    ->put
    ?

    cheers

  48. Very nice pace to these training courses - snappy, no time to get boring. All training videos should be like this. Well done.

  49. Excellent explanation, one suggestion I have which you are probably going to explain soon, is with this case you probably wouldn’t want the tag to navigate you to a different page (in this case you would navigate to domain.com#) using

    $(’a#add’).click(function(event)){
    event.preventDefault();
    }

    Would prevent the a tags default operation

  50. This is now my favourite website, I love these tutorials.

  51. MegaTight!
    Thanks for being super cool!

  52. Excellent tutorials!

    I have sumed up everything as i watch every tut on my test page:

    http://www.arvag.net/test/jquery

    one little but i noticed so far is function you use for removing last li in this tutorial, if you remove all instances of li and keep pressing “Remove” button and then start to pressing “Add” button, “index” will start from some negative number… :P

    so just simple workaround this would be this :)

    if (i != 0){
    i–;
    };

  53. Jeffrey,

    Having so much fun with your video tutorials! I learned something day by day!

Add a Comment

Name Email Website

Note: The avatars shown next to comments are Gravatars. You can get a Gravatar account for free and any other site that supports it will show your avatar too!

 

Trackbacks

Leave a Trackback