Tags
Asked 1 years ago
24 Apr 2023
Views 114
david

david posted

what is equivalent document.createElement in jQuery ?

i am tried to use document.createElement to create element but seeking something very more efficient way to do it by jQuery ?
denyy

denyy
answered May 1 '23 00:00

at jQuery, you can create a new HTML element using the $() function , also known as the jQuery function, and passing in the element's tag name as a string.

For example, to create a new div element, you can use the following code:


var newDiv = $('<div>');
This code creates a new jQuery object that contains a div element. You can then use jQuery methods to modify the element's attributes or add it to the DOM.

To add attributes to the new element, you can use the .attr() method, as shown below:



var newDiv = $('<div>').attr('id', 'myDiv').addClass('my-class');

This code creates a new div element with an id attribute of myDiv and a CSS class of my-class.

To add the new element to the DOM, you can use jQuery methods such as .appendTo(), .prependTo(), or .insertAfter(), as shown below:


newDiv.appendTo('body');
This code adds the new div element to the end of the body element.
Post Answer