Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a DOM element to a jQuery element?

Tags:

jquery

I am creating an element with document.createElement(). Now how can I pass it to a function that only takes a Jquery object?

$("#id")  

I can not use it, as the element has not been rendered in the page yet.

like image 801
Tanmoy Avatar asked Mar 09 '09 11:03

Tanmoy


People also ask

How can create DOM element in jQuery?

Answer: Use the jQuery append() or prepend() method You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.

How do I select a specific DOM node in jQuery?

If you have a variable containing a DOM element, and want to select elements related to that DOM element, simply wrap it in a jQuery object. var myDomElement = document. getElementById( "foo" ); // A plain DOM element. $( myDomElement ).

Is it possible to access the underlying DOM element using jQuery?

The Document Object Model (DOM) elements are something like a DIV, HTML, BODY element on the HTML page. A jQuery Selector is used to select one or more HTML elements using jQuery. Mostly we use Selectors for accessing the DOM elements.

What is the difference between jQuery elements and DOM elements?

A DOM element represents a visual or functional element on the page which was created from the original HTML document. jQuery now is a Javascript library that makes manipulating the DOM easier than with pure Javascript by offering a number of convenience shortcuts.


2 Answers

var elm = document.createElement("div"); var jelm = $(elm);//convert to jQuery Element var htmlElm = jelm[0];//convert to HTML Element 
like image 117
Marius Avatar answered Oct 08 '22 06:10

Marius


What about constructing the element using jQuery? e.g.

$("<div></div>") 

creates a new div element, ready to be added to the page. Can be shortened further to

$("<div>") 

then you can chain on commands that you need, set up event handlers and append it to the DOM. For example

$('<div id="myid">Div Content</div>')     .bind('click', function(e) { /* event handler here */ })     .appendTo('#myOtherDiv'); 
like image 37
Russ Cam Avatar answered Oct 08 '22 06:10

Russ Cam