How do I access the core HTML DOM element from a JQuery Selector?
For example, the following code:
$(document.body).appendChild(x);
will not work because the DOM object that $(document.body) is referring to is wrapped around by a JQuery Selector Object.
(Please don't suggest that I can use jQuery's append() instead, it's just for an example)
jQuery Objects are arrays of native DOM elements. So try this:
$(document.body)[0].appendChild(x)
On the other hand, if you have a native DOM element, you can just wrap it in a jQuery Object to use jQuery's methods on it.
var x = document.getElementsByTagName('div');
$(x).remove(); // wrap it with $ to use jQuery methods.
.get() should do the work like so :
$(document.body).get(0)
Since jQuery is built on top of Sizzle you can refer to the Sizzle's documentation under this link.
Since $ is just an alias, you can refer to the documentation:
$(String selector[, DOMNode context[, Array results]])
The main function for finding elements. Uses querySelectorAll if
available.
the above will return an array, even if there is only one element. So if you want to refer to the one element exactly, you have to use array index like:
$(document.body)[0].appendChild(x);
this is a native DOM code which should definitely work:
document.body.appendChild(x)
Related
I'm trying to get the children of the nth element returned by a jquery call. For example:
var kids = $('div')[7].children();
However, I keep getting this error with respect to children():
Uncaught TypeError: object is not a function
Can someone explain why this happens? children() works fine as long as I'm not calling it on an indexed element.
It's because it is no longer a jQuery object after you specify an index [7]. Thus, you are calling a jQuery method on a DOM element (which doesn't work).
You could use the .eq() method instead:
$('div').eq(7).children();
You could also use:
$($('div')[7]).children();
It's worth pointing out that this would work because the DOM element is wrapped in $() - thus turning it into a jQuery object.
You're using children method in javascript object i.e. $('div')[7]. To work with jquery method you need to use jquery object instead of javascript object.
Use eq method:
var kids = $('div').eq(7).children();
When you use array syntax with a jquery list you get back a document node, not a jquery element. Use $('div').eq(7).children() instead.
Say I have a map on an array of elements. The callback function takes the index and the value at that position in the array.
If I wrap the array element that the callback receives in $(), it behaves as I expect. If I use it without wrapping it in $(), it gives an error.
var nonHiddenElements = $( "form :input" ).not(':hidden');
nonHiddenElements.map(function(index, element){
input_id = $(element).attr('id'); // this works
input_id = element.attr('id') ; // this gives an error
})
Can someone explain how this works.
Is this a jQuery quirk, or a JavScript thing?
What type of objects does my nonHiddenElements array contain exactly?
What is element that gets passed to the callback?
And mainly what is the $() doing?
You need to understand how jQuery actually works. I will try to explain it briefly.
$ is nothing but a normal javascript function. jQuery === $, is just a function with a fancy name. This function does a lot of different things, depending on what you pass in it. For example if you pass a string it will be treated as CSS selector and jQuery internals will try to find corresponding DOM elements. Or if you pass a string starting with < and ending with > jQuery will create a new DOM element by provided HTML string.
Now if you pass a DOM element or NodeCollection of DOM elements, it/they will be wrapped into jQuery instances so that they can have a jQuery prototype methods. There are many prototype methods jQuery offers. For example text, css, append, attr - those are all methods of jQuery prototype. They are defined basically like this (simplified):
jQuery.prototype.text = function() { ... }
Normal DOM elements don't have those convenient methods jQuery provides. And inside of methods like map or each if you check this value or element parameter like you do, you will see that they are actually not jQuery instances:
element instanceof jQuery // => false
and of course you can't use instance methods with not an instance.
So in order to use jQuery prototype methods you need have a jQuery instance, which you can obtain if you call jQuery function with DOM element passed in it:
$(element) instanceof jQuery // true
Javascript is a programming language.
jQuery is a JavaScript Library.
With jQuery:
$("some element")
In native JavaScript you would have to do something like this.
getElementById('elementByID')
Explained in detail here: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
MDN is a great resource for beginners. https://developer.mozilla.org/en-US/docs/Web/JavaScript
Is there a way to have get() returning a jQuery object instead of "just" the DOM element?
Example:
$("div").get(0) returns [<div></div>] instad of <div></div>.
I'd like to prevent overwrapping like $($("div).get(0)) because the query will get a little bit longer than the example and I fear the readability gets lost. I'd rather not use variables to save unnecessary DOM elements in the RAM, either.
Use eq() to return the jquery object instead of get()
$("div").eq(0)
Given a jQuery object that represents a set of DOM elements, the .eq()
method constructs a new jQuery object from one element within that
set. The supplied index identifies the position of this element in the
set, jQuery doc
You would use eq:
$("div").eq(0)
Use eq() instead , which will return jQuery object
$("div").eq(0)
Also try this also:
$('div:first')
Is there any way to get the selector for a jquery object
e.g in firefox I see a jquery object as [p.basket]
but there seems to be no way in jquery that I can get this selector?
Is there any way?
Phil
If a jQuery object was created with a selector string, then you can just look at its "selector" property. However, not all jQuery objects are so constructed. Thus you should make sure to check for null.
edit — if your jQuery object was not constructed with a selector, then there simply is not a selector available. The library does not have any built-in way of creating a selector that matches the set of elements it contains. You could do that yourself, though it's not clear why it would be useful; once you have a reference to the DOM elements (which you do if the jQuery object isn't empty), isn't that more useful?
Is the selector property what you want?
Why is it when I select html elements using .get(i) or similar methods, I am unable to use methods on those elements like the .removeClass() or .html().
I would think that the code below is perfectly valid, yet neither lines work. What do I need to do to apply jQuery methods to an element based on its ordinal index in the DOM?
($('li').get(0)).removeClass('yourClass');
$('li')[0].addClass('myClass');
Here is an example of the issue: http://jsfiddle.net/KcNWy/2/
Check the documentation:
The .get() method grants us access to the DOM nodes underlying each jQuery object.
You can DOM object into jQuery object again: $($('li').get(0)). Or, better yet, use eq: $('li').eq(0).
And also a debugging hint. You can use in firefox/chrome/safari console.log(myObject) to see what's actually returned.
The get() method passes back the DOM object
Retrieve the DOM elements matched by the jQuery object.
Try this instead:
$("li:eq(" + 0 + ")").removeClass("yourClass")
Working example: http://jsfiddle.net/KcNWy/6/