5

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:

$.create('#hello').insertAfter('#test');

would generate the following:

<div id="test">This element already existed in the DOM.</div>
<div id="hello"></div>

Or, better yet, for more complex operations:

$.create('#test.a.b');

for:

<div id="test" class="a b"></div>

Obviously, more complex operations like :selected or :nth-child or :not() and all of those need not be implemented.

Is anyone aware of a solution?

Thanks.

M Miller
  • 5,364
  • 9
  • 43
  • 65
  • Possible duplicate of [Can jQuery create an element by a selector?](https://stackoverflow.com/questions/3518650/can-jquery-create-an-element-by-a-selector) – KyleMit Sep 19 '17 at 18:59

4 Answers4

5

To create <div id="hello"></div>

try

$('<div id="hello"></div>').appendTo('body');

To create <div id="test" class="a b"></div> same as

$('<div id="test" class="a b"></div>').appendTo('body');

$('<div id="test" class="a b"></div>') 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('<div id="test" class="a b"></div>', '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

The System Restart
  • 2,873
  • 19
  • 28
  • Your function was what I was looking for; I suppose then that jQuery does not have default functionality to perform such an operation, which is understandable, because it wouldn't have common uses. Anyways, thanks for your help, saves me the headache of writing the function myself! :) – M Miller May 15 '12 at 16:45
  • @JohnGalt WC buddy. Glad to help you. – The System Restart May 15 '12 at 16:47
  • Hello. I loved your solution, but you have to update a detail: newelement = $('<'+el+'/>'), On your demo, try to add a new div to the html pan and see what happens. Thank you again! – Cristopher Feb 05 '15 at 17:43
5

I actually created one earlier, still a little buggy, but would work for the case you are thinking of, just using it like

$.jseldom('#test.a.b')

and you can even use it with sibling selector

$.jseldom('#test #abc .child +.sibling-of-child')

https://github.com/shekhei/jseldom

use it if you find it useful, and report all the issues there :P I am really hoping to make it into something that would benefit people :)

Alfred
  • 21,058
  • 61
  • 167
  • 249
2

I don't see something out there that would create elements off of css selector syntax. JQuery does let you create and add elements, but the syntax is not based off of the css selectors as in your example. For instance to add a #hello div with class a and b after the #test div, you can use .after():

$('#test').after("<div id='hello' class='a b'>Hello</div>");​​​​​​​​​

jsfiddle: http://jsfiddle.net/septerr/RmAW6/

or

$('#test').after('<div>Hello</div>').attr('id', 'hello').addClass('a').addclass('b');​

jsfiddle: http://jsfiddle.net/septerr/EQjLE/

septerr
  • 6,445
  • 9
  • 50
  • 73
0

Just insert the html tags into it

$("<div id='hello'></div>")

See here for further details jQuery document.createElement equivalent?

Community
  • 1
  • 1
AlanFoster
  • 8,156
  • 5
  • 35
  • 52