[Solved-6 Solutions] jQuery document.createElement equivalent - javascript tutorial



Problem:

How jQuery document createElement equivalent ?

Solution 1:

Here is a couple of examples are given below :

var $example = $( XMLDocRoot );
var $element = $( $example[0].createElement('tag') );
// Note the [0], which is the root

$element.attr({
id: '1',
hello: 'world'
});

var $example.find('parent > child').append( $element );

Solution 2:

Use this code:

var div = $('<div/>');
div.append('Hello World!');

To create a DIV element in jQuery.

Solution 3:

Use this code:

$('<div/>',{
    text: 'Div text',
    class: 'className'
}).appendTo('#parentDiv');

Solution 4:

HTML elements needs to add in a jQuery constructor $() will return a jQuery object to built HTML, is suitable for being appended into the DOM by using jQuery's append() method.

var t = $("<table cellspacing='0' class='text'></table>");
$.append(t);

To specify any arbitrary HTML, including class names or other attributes, to find more concise than using createElement and then setting attributes like cellSpacing and className via JS.


Solution 5:

  • If we use $(string), jQuery will examine the string need to select a html tag or create a new element. By using $.parseHTML(), in jQuery want to create a new element.
    var userInput = window.prompt("please enter selector");
    $(userInput).hide();

Using $.parseHTML() :

var a = $('<div>')
// a is [<div></div>]
var b = $.parseHTML('<div>')
// b is [<div></div>]
$('<script src="xss-attach.js"></script>')
// jQuery returns [<script src="xss-attach.js"></script>]
$.parseHTML('<script src="xss-attach.js"></script>')
// jQuery returns []

Note that a is a jQuery object while b is a html element:

a.html('123')
// [<div>123</div>]
b.html('123')
// TypeError: Object [object HTMLDivElement] has no method 'html'
$(b).html('123')
// [<div>123</div>]


Solution 6:

Using jquery, don't assign properties passed to the second object in the following method. Using document.createElement('div') together with jQuery is faster

$( document.createElement('div') ,{
    text: 'Div text',
    'class': 'className'
}).appendTo('#parentDiv');


Related Searches to jQuery document.createElement equivalent - javascript tutorial