How to get a DOM Element from a jQuery selector?
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest
.
Create DOM element from jQuery selector
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
using jQuery selector with a dom element
You want
function submit_form(obj)
{
var form1 = $(obj).closest("form")[0];
alert (form1.id);
}
The result of jQuery selection/traversal functions always is an array, possibly with one element only, but still an array. Index into the array to get actual DOM elements.
However, you can do this without jQuery as long as obj
is an input/select/textarea element.
function submit_form(obj)
{
var form1 = obj.form;
alert (form1.id);
}
For the sake of completeness, you could also stay within jQuery and do
function submit_form(obj)
{
var $form1 = $(obj).closest("form");
alert ( $form1.attr("id") );
}
Jquery select DOM elements and access inner elements
You need to use .find
or .children
to find children/nested elements.
$(ele).children('label') // takes just direct children
$(ele).find('label') // take all nested labels
Why use jQuery(selector).get(0) instead of jQuery(selector)[0] to get DOM element?
.get
allows you to use negative indices. For example:
<span>1</span>
<span>2</span>
<span>3</span>
$("span").get(-1);
refers to the third span
.
But if you don't need that feature and only want to select one element .get(0)
and [0]
are the same. Notice the this[num]
:
// jQuery code
get: function (num) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
(num < 0 ? this[this.length + num] : this[num]);
},
Retrieving native DOM elements from jQuery objects?
When you find elements with jQuery, you can get them with the "get" function:
var regularElement = $('#myElementId').get(0);
Inside a ".each()" function, the "this" pointer refers to a "real" element:
$('input.special').each(function() {
var type = this.type;
this.value = "exploding balloon";
// etc
})
Using jQuery doesn't make Javascript "different." It is Javascript, and the DOM is still the DOM.
Getting a jQuery selector for an element
I see now that a plugin existed (with the same name I thought of too), but here's just some quick JavaScript I wrote. It takes no consideration to the ids or classes of elements – only the structure (and adds :eq(x)
where a node name is ambiguous).
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.name;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
(License: MIT)
Related Topics
What's the Difference Between Window.Location and Document.Location in JavaScript
Check Image Width and Height Before Upload with JavaScript
Dynamically Add Script Tag with Src That May Include Document.Write
How to Compute the Sum and Average of Elements in an Array
Jqgrid Incorrect Select Drop Down Option Values in Edit Box
What Is the Stability of the Array.Sort() Method in Different Browsers
Function with Foreach Returns Undefined Even with Return Statement
JavaScript Closures VS. Anonymous Functions
How to Dynamically Change Header Based on Angularjs Partial View
Check If a Variable Is of Function Type
Generic Deep Diff Between Two Objects
Mongodb, Remove Object from Array
The Value of "This" Within the Handler Using Addeventlistener
Function Declarations Inside If/Else Statements