Create DOM element from jQuery selector

后端 未结 4 1924
野性不改
野性不改 2021-01-13 08:48

I was wondering if it were possible to, instead of selecting an element from the DOM via a jQuery selector, if I can create one instead.

For example:



        
4条回答
  •  醉梦人生
    2021-01-13 09:12

    To create

    try

    $('
    ').appendTo('body');

    To create

    same as

    $('
    ').appendTo('body');

    $('

    ') will create new element but not add it to DOM.

    To add that element you need to use append() or appendTo() or insetAfter() or insertBefore() and so on.

    It is better to use a function to:

    function createElement(el, target) {
       $(el).appendTo(target);
    }
    

    use the function like:

    createElement('
    ', 'body');

    You can also append newly created element to any other target instead of body.

    I think following function will help you:

    function createElement(el, prop, target) {
      var props = prop.split('.'),
          newelement = $(el),
          id = '',
          className = '';
        $.each(props, function(i, val) {
            if(val.indexOf('#') >= 0) {
               id += val.replace(/^#/, '');
            } else {
               className += val + ' ';
            }
        });
        if(id.length) newelement.attr('id', id);
        if(className.length) newelement.attr('class', className.trim());
    
        $(newelement).html('Newly born').appendTo(target);
    }
    
    createElement('div', '#test.a.b', '#con');​ // will work for #test.a.b or, .a.b or, #test.a
    

    DEMO

提交回复
热议问题