Best way to add DOM elements with jQuery

后端 未结 7 905
南笙
南笙 2020-12-05 02:08

So I\'ve seen three ways to add html/DOM elements to a page. I\'m curious what the pros and cons are for each of them.

1 - Traditional JavaScript

相关标签:
7条回答
  • 2020-12-05 02:24

    If you already have a template element that you want to copy then by all means use clone().

    But if you want to create an element from scratch then there's basically two methods which I think you alluded to:

    1. Create DOM elements as objects (using createElement for example).
    2. Create DOM elements as HTML (using innerHTML or jQuery's html() for example).

    First if either of the methods is more intuitive or easier to write for you, I'd recommend just doing that.

    Otherwise benefits of using the latter is that it is cleaner if the element has many children. For example, try to make a table row with 6 columns, each with a different class using the first method. Your code will be much longer than if you used the second method.

    As far as performance goes this is a good guide http://andrew.hedges.name/experiments/innerhtml/ but the short answer is for most cases the differences are quite negligible. A good guide for performance in general as well is: http://www.artzstudio.com/2009/04/jquery-performance-rules/. The 6th tip has to do with DOM manipulation.

    0 讨论(0)
  • 2020-12-05 02:24

    If you have jQuery already available, use it. If you don't want to host it, use Google's hosted version. In the end is it always calling the native javascript createElement or innerHTML methods anyway. So I'd use #2, and #3 if I specifically had to clone an existing element on the page.

    0 讨论(0)
  • 2020-12-05 02:26

    The cleaner way to do is using jQuery.

    $('tr').addClass('myClass') like syntax. This is easy to read, understand and maintain.

    0 讨论(0)
  • 2020-12-05 02:27

    If you're working with large amounts of HTML you want to reuse then I'd suggest you look at: http://api.jquery.com/jQuery.template/ which is final, but will be replaced by something better.

    I use it in a production environment and it's great, as for smaller pieces of html what sp. said is the best way

    0 讨论(0)
  • 2020-12-05 02:31

    If you are using jQuery 1.4 the best way is the following:

    $("<a/>", {
        id: 'example-link',
        href: 'http://www.example.com/',
        text: 'Example Page'
    }).appendTo("body");
    
    0 讨论(0)
  • 2020-12-05 02:42

    Clone existing Content...

    var $html = $template.clone();
     $html.find(''); ///after change content...  

    Because of clone content is with 'DOM' properties. Then u can change this tags,properties,value then append it..

    0 讨论(0)
提交回复
热议问题