Conclusion: The $(document. createElement('div')); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
jQuery attribute methods allows you to manipulate attributes and properties of elements. Use the selector to get the reference of an element(s) and then call jQuery attribute methods to edit it. Important DOM manipulation methods: attr(), prop(), html(), text(), val() etc.
All HTML elements have inner HTML properties. The . html() jQuery method retrieves the HTML content of the first element in the particular set of matched elements. Remember: jQuery innerHTML does not exist as a function.
From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:
var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));
alert( dom_nodes.find('input').val() );
DEMO
var string = '<div><input type="text" value="val" /></div>';
$('<div/>').html(string).contents();
DEMO
$('<div/>')
is a fake <div>
that does not exist in the DOM$('<div/>').html(string)
appends string
within that fake <div>
as children.contents()
retrieves the children of that fake <div>
as a jQuery object.find()
work then try this:var string = '<div><input type="text" value="val" /></div>',
object = $('<div/>').html(string).contents();
alert( object.find('input').val() );
DEMO
As of jQuery 1.8 you can just use parseHtml to create your jQuery object:
var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));
I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/
It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.
var jQueryObject = $('<div></div>').html( string ).children();
This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.
There is also a great library called cheerio designed specifically for this.
Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <h2 class="title welcome">Hello there!</h2>
I use the following for my HTML templates:
$(".main").empty();
var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");
$(".main").append(final.html());
Note: Assuming if you are using jQuery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With