Removing $() jQuery wrapper to just get raw JS element [duplicate] - javascript

This question already has answers here:
How to get a DOM Element from a jQuery selector?
(4 answers)
Closed 8 years ago.
Random just out of curiosity question:
Let's say for whatever reason I get an element back from a function
$(element)
But I want to remove the $( __ ) jQuery wrapper to leave the regular DOM Element:
element
Is this possible? (I'm sure it'd be smart to test $(element).length() to make sure it isn't more than 1 thing inside beforehand too...
jsFiddle

var firstElem = $(element)[0];
or
var firstElem = $(element).get(0);
Calling get() without an index gives you an array of the elements.
Reference: jQuery get()

DOM elements are stored as properties at numeric zero-based indices, so you access them just like you would for any other object.
$jqObj[0];
Or get a full Array of elements using toArray()
$jqObj.toArray();

Fiddle: http://jsfiddle.net/xHj5d/2/
removeJWrapper($('#ohHeyo'));
function removeJWrapper (el) {
console.log(el[0]);
}

Related

JS how to get twitter's name [duplicate]

This question already has answers here:
How to Get Element By Class in JavaScript?
(12 answers)
Closed 9 years ago.
Using JavaScript, we can get element by id using following syntax:
var x=document.getElementById("by_id");
I tried following to get element by class:
var y=document.getElementByClass("by_class");
But it resulted into error:
getElementByClass is not function
How can I get an element by its class?
The name of the DOM function is actually getElementsByClassName, not getElementByClassName, simply because more than one element on the page can have the same class, hence: Elements.
The return value of this will be a NodeList instance, or a superset of the NodeList (FF, for instance returns an instance of HTMLCollection). At any rate: the return value is an array-like object:
var y = document.getElementsByClassName('foo');
var aNode = y[0];
If, for some reason you need the return object as an array, you can do that easily, because of its magic length property:
var arrFromList = Array.prototype.slice.call(y);
//or as per AntonB's comment:
var arrFromList = [].slice.call(y);
As yckart suggested querySelector('.foo') and querySelectorAll('.foo') would be preferable, though, as they are, indeed, better supported (93.99% vs 87.24%), according to caniuse.com:
querySelector(all)
getElementsByClassName
Don't use w3schools to learn something
Refer to MDN for accurate information
Another option is to use querySelector('.foo') or querySelectorAll('.foo') which have broader browser support than getElementsByClassName.
http://caniuse.com/#feat=queryselector
http://caniuse.com/#feat=getelementsbyclassname
You need to use the document.getElementsByClassName('class_name');
and dont forget that the returned value is an array of elements so if you want the first one use:
document.getElementsByClassName('class_name')[0]
UPDATE
Now you can use:
document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)
or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).
you can use
getElementsByClassName
suppose you have some elements and applied a class name 'test', so, you can get elements like as following
var tests = document.getElementsByClassName('test');
its returns an instance NodeList, or its superset: HTMLCollection (FF).
Read more

Get the outer HTML of a detached JQuery object [duplicate]

This question already has answers here:
Get selected element's outer HTML
(30 answers)
Closed 6 years ago.
I'm creating a html node by jQuery (the sample is of tag <input> but can be of any type):
var x = $("<input>");
Then I add its attributes through a series of .prop() function:
x.prop("id", ...).prop("class", ...);
Now a certain plugin does not support JQuery object, but rather the HTML string so I invoke the plugin through this:
var n = plugin.method1(x.html())
Which I though will work but .html() returns an empty string. Although some said it will be resolved if I append it first on the DOM tree. How can I get its HTML string without appending it first in the DOM tree?
You can use .prop() to get outerHTML property.
x.prop('outerHTML');
var x = $("<input>");
x.prop('id', 'yahooooooooo');
console.log(x.prop('outerHTML'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Bit simpler to index the HTMLElement behind it and access the outerHTML property like this:
x[0].outerHTML

getElementById vs $('#element')

Before today, I thought that getElementById and $('#element') accomplished the same thing. However, when I tried the following:
// Assuming I have jQuery imported already
var $scrollHolder = $('#element');
var scrollDiv = document.getElementById("element");
scrollDiv.scrollTop = scrollDiv.scrollHeight;
//$scrollHolder.scrollTop = $scrollHolder.scrollHeight;
The commented line didn't work, and the uncommented line did. Do the two methods listed above return different things, or is there an error in my code? Should the commented line be working? I'm very confused and would appreciate insight. Thank you.
you have to get the DOM element from jQuery Object
$scrollHolder[0].scrollTop = $scrollHolder[0].scrollHeight;
or
.get( index )
$scrollHolder.get(0).scrollTop = $scrollHolder.get(0).scrollHeight;
$('#element'); is jQuery Object. It creates an array of matched Objects . But here you have id-selector so you only get one Object you can refer to the Native DOM object by using array index [index] or using .get(index).
document.getElementById("element"); is a native DOM Object
FYI
jQuery way of doing it.
.scrollTop()
.prop()
$scrollHolder.scrollTop($scrollHolder.prop('scrollHeight'));
$('#id) returns jquery objects which doesn't have native DOM properties and document.getElementById('id') returns you a native DOM element which has scrollTop property.
Note that you can make any DOM element act as jquery object by wrapping it with $( ) and you can make jquery object to DOM element by accessing index.
An other solution is using the correct jQuery-Wrapper for that:
$scrollHolder.scrollTop($scrollHolder.scrollHeight);
JQuery selector method always returns an Array of elements.
So commented line will not return what you expect.

You can wrap $() around an array of DOM elements, or around a jQuery object, but not around an array of jQuery objects

Not really sure how to phrase this question so it's generic enough. (and will rephrase, after I know what I'm asking). The problem, I believe deals with variables in a JQuery .find() function.
Problem: you can wrap $() around an array of DOM elements, or around a jQuery object, but not around an array of jQuery objects
The best I can do, at this time, is provide an example here
The problem code in the previous fiddle, is here:
////////////////Neither of the following works////////////////
//nodelevel = nodesWithMinuses.find('div.node.level' + levelnumber);
nodelevel = $(nodesWithMinuses).find('div.node.level' + levelnumber);
////////////////Neither of the previous works////////////////
Apparently you can wrap $() around an array of DOM elements, or around a jQuery object, but not around an array of jQuery objects.
Try changing this line:
var nodeWithMinus = thisplusminus.parent().parent();
to this:
var nodeWithMinus = thisplusminus.parent().parent()[0];
This will extract the DOM element and turn nodesWithMinuses into an array of DOM elements.
The variable nodesWithMinuses is an array of jQuery objects. You cannot apply jQuery method to anything else then a jQuery object. You have 2 options : either you declare nodesWithMinuses as a jQuery object and add objects to it via the add method :
var nodesWithMinuses = $();
//...
nodesWithMinuses.add(element);
// instead of nodesWithMinuses.push(element);
either find a way to convert the array to a jQuery object :
$($.map(nodesWithMinuses,function(el,i){return el.get(0)})).find('div.node.level' + levelnumber);
or traverse the array and search for the element in each object at a time :
var result = $();
$.each(nodesWithMinuses,function(i,el){
result.add(nodesWithMinuses.find('div.node.level' + levelnumber));
});
console.log(result);
In your code, nodeWithMinuses is an array but you're trying to wrap it in the jQuery function. That doesn't work on arrays. Using a variable in jQuery's find function is fine.

How to create an empty jQuery result [duplicate]

This question already has answers here:
Getting an empty JQuery object
(4 answers)
Closed 5 years ago.
Edit: As of jQuery 1.4, using $() will work as described below.
I need to loop through an array and create a number of elements which I want to have in a single jQuery result object.
for (var i = 0; i < 10; ++i) {
$myJQueryObj = $myJQueryObj.add($("<span>blahblah</span>"));
}
The problem with this, however, is that you need a jQuery object to begin with, and you obviously want to start it empty. In the above example, how should I initialise $myJQueryObj ?
The following examples do not work, as they all select the document object:
$('')
$()
$(null)
$(false)
These do work... but...
$('#nonExistantElement') // yuck
$().slice(0,0) // surely there's a nicer way?
Is there a better way?
Yep. Try $([]). The reason $() doesn't work is because that jQuery expects a context, and without any supplied, will default to document as the context. Many things depend on this assumption being true, so changing $() to mean "give me the empty set" would be problematic at best.
Ah, I figured it out just after I wrote the question. Here's what I found, in case anyone else is interested:
$([])

Categories

Resources