I know that Enumeration by ClassName can be used for multiple objects, and Enumeration by ID can be used for particular objects.
But is there any other specific difference between the two methods?
getElementsByName:
This method returns the collection of elements whose name value is
given by elementName (The name attribute value for an element.)
This method is case sensitive.
getElementById:
Returns the Element whose ID is given by elementId.
If no such element exists, returns null.
Note: Behavior is not defined if there are more than one element has the same ID.
You may consider also Performance.
Referring to this link, it looks like getElementByClassName is faster.
But it really depends on the specific page you are on, and the browser engine.
Related
What is the type of the variable "element" in this snippet?
I thought it is a number (an ID or something), but now, I have no idea.
The code works, but I don't understand, why the var element can be used in a for cycle, like an array. Is there any explanation about this?
<script type="text/javascript">
function showAtrributes() {
var element = document.getElementById("videos");
var listAttributes = "";
for(var attribute in element) {
var valueOfAtrrib = element.getAttribute(attribute);
listAttributes = listAttributes + attribute + ": " + valueOfAttrib + "\n";
}
alert(listAttributes);
}
</script>
The getElementById() method returns the element that has the ID
attribute with the specified value.
[....]
Returns null if no elements with the specified ID exists.
So it returns an HTMLElement Object
source
What is the return type of document.getElementById()
Element. It returns a reference to the actual object for the element in the DOM (or null if none was found with that id). Details:
Spec for Element
Spec for getElementById
Element on MDN
getElementById on MDN
I thought it is a number (an ID or something)
No, that's "video" (the string you used to look it up). It's also accessible from the id property of the Element object.
The code works, but I don't understand, why the var element can be used in a for cycle, like an array.
for-in isn't primarily for use on arrays, it's for use on objects. The only reason it works on arrays is that arrays are objects. (See this question's answers and this page on MDN for more on that.) DOM elements are objects, so you can loop through their enumerable properties via for-in.
The return type of document.getElementById() is Element Object or null. Please Refer the following link from MDN:
It looks like you are really questioning why the for loop works, not what kind of object getElementById returns. Read this article:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
The for( var in ....) syntax causes Javascript to iterate over the properties of the object specified by ....
The return type can be anything that the programmer of a Web Browser defines to the JS VM library used, to create a specific implementation of Javascript. For instance, the webcwebbrowser which uses SpiderMonkey returns a JSObject of HTMLElement JSClass which it gets by calling CreateJSObject on the underlying internal HTMLElement object. The JSObject is the internal VM library representation of objects visible to JS scripts, such as a HTMLElement. A HTMLElement in a script is actually accessing a JSObject logically instantiated from the HTMLElement JSClass, where JSObject and JSClasses are C++ classes. The HTMLElement JSObject also has a corresponding C++ native marshalled object of class HTMLElement.
I have read the JQuery documentation, and while much attention is devoted to what you should pass the function, I don't see any information on what it actually returns.
In particular, does it always return an array, even if only one element is found? Does it return null when nothing is found? Where is this documented?
I understand that jquery methods can be applied to the return value, but what if I want to just use the return value directly?
From Rick Strahl's description:
The jQuery Object: The Wrapped Set:
Selectors return a jQuery object known
as the "wrapped set," which is an
array-like structure that contains all
the selected DOM elements. You can
iterate over the wrapped set like an
array or access individual elements
via the indexer ($(sel)[0] for
example). More importantly, you can
also apply jQuery functions against
all the selected elements.
About returning nothing:
Does it always return an array? Does it return null?
You always get the same thing back, whether or not it has any contents is the question. Typically you can check this by using .val() (e.g. $('.myElem').val())
It doesn't return an array, it returns a jQuery object. The jQuery object is what contains all the special jQuery methods.
It never returns null, or another type. If one element is found, the jQuery object will have only one child. If no elements are found, the jQuery object will be empty.
As another answerer mentioned, it always returns the jQuery object.
This object always contains an array of elements (even if it is an empty array, or an array with just one object).
If you'd like to use the returned object "directly", as in, as a plain element, you can do one of the following:
$('selector')[0] // element
$('selector').get(0) // element
$('selector').length // number of elements in the array
The jQuery function (i.e. "$") always returns a jQuery object in every instance.
From the jQuery documentation:
The jQuery object itself behaves much like an array; it has a length property and the elements in the object can be accessed by their numeric indices [0] to [length-1]. Note that a jQuery object is not actually a Javascript Array object, so it does not have all the methods of a true Array object such as join().
The fact that $() always returns the jQuery function lets you chain jQuery function calls judiciously.
Jquery selector mechnism
$("..") , the jquery selector, is used to select matched elements.
Return value
It always return an array-like jquery object, which has a length property,
Call method on returned jquery object
Methods of jquery could be called on the object, and apply to those selected elements,
Access original element by index
The selected elements, are store as property of the object, their property name are index numbers start from 0,
thus could be accessed by index, start from 0,
after get the original element, you can treat it as if get by document.getElementXxx().
Wrap an original element to a jquery object
After get the original element, you can wrap it to be a jquery object, by calling $(originalEle),
then you can call jquery methods on the wrapped object.
According to firebug, it returns an array of objects that match to your selector. But this array is a jQuery object, that more methods than a simple Array.
Their documentation lists a few of the core calls you can use with "$" and what they return
Why does function getElementsByClassName() work on javascript objects, but "getElementById" kick back "not a function"?
var divBox= makeDivBox(divParams);
var divContents = divBox.getElementById("divID");
errors : divBox.getElementById is not a function
But :
var divContents = divBox.getElementsByClassName("divClass")[0];
has no issue. Why?
edit: see similar courtesy of #rajuGT
You appear to have a couple issues.
divBox.getElementById("divID"); doesn't work because getElementById() is only a method on the document object. It is not a method on other types of objects. So, the divBox element does not have that method. You could use document.getElementById("divID") instead if there was only one divID in the entire document and if divBox was already inserted into the document.
var divContents = divBox.getElementsByClassName("divClass")[0]; works because .getElementsByClassName() is a method on all DOM objects so it works when you call it on divBox.
You call getElementById() like this document.getElementById("someID").
If you want to find something in a particular part of the subtree, you can use element.querySelectorAll("#someID") or if you want to have more than one object with a given identifier, then you can use a class name and use functions that find objects with a given class name.
As to your specific questions:
divBox.getElementById is not a function
That is because geetElementById() is only a method on the document object and divBox is not a document object so it does not have that method, therefore you get the error you are seeing.
Why does this have no issue:?
var divContents = divBox.getElementsByClassName("divClass")[0];
That is apparently because divClass is a class name, not an id value and all HTML elements contain the getElementsByClassName() method so you can call it on divBox just fine.
It is because the id should be unique to the page/document.
So calling from the document and from the element should be same always. Hence providing the method for other DOM nodes is not useful at all and hence the getElementById is not available/added to the other DOM elements.
where as getElementsByClassName returns all DOM elements for the given className when called on document node. If called with any other DOM element, only child nodes which have the given className DOM nodes will be returned. Here, the behavior is different compared to the getElementById, hence this method is available to all DOM nodes.
The reason I ask is because I'm thinking of storing a bunch of DOM nodes in this huge and multi-dimensional array I have.
Cost: takes up space in memory. The question is how much space, and that depends on whether I'm getting references or actual DOM nodes.
Benefits: 1) It'll make my code a lot simpler. 2) I could avoid traversing and instead just reference the DOM node from my array.
Thoughts?
From jQuery site:
… jQuery() — which can also be written as $() — searches through the
DOM for any elements that match the provided selector and creates a
new jQuery object that references these elements
jQuery Documentation
jQuery returns the actual DOM Node. It's why you will find yourself writing $(this) most of the time. This is because you want to wrap your node in jQuery to be able to use some jQuery methods. However, it's recommended (almost in the guidelines) to cache your DOM nodes through references. For example,
var div = $('div');
div.dosomeMethod();
div.append();
This ensures that you are not traversing the entire DOM tree (the expensive DOM part) whenever you're trying to access some element. Whenever you do updates, ensure you're doing them as a batch.
in this example I show how to clone existing DOM element to object in memory, also create object in memory without pushing it to body, created collection objects, appended elements from collection to body and keep referenced objects, removed from body.
and so many operations...
var $newElement1 = $(selector).clone(); // create new element from existing and store in memory
var $newElement2 = $('<div>blabla</div>'); // create new element from html code and store in memory
var elements = [];
elements.push($newElement1);
elements.push($newElement2);
for(var i in elements) {
elements[i].appendTo($('body'));
}
$newElement1.remove(); // will remove it from body
** but I recommend You to use frameworks like: angularjs, reactjs, emberjs to save Your time
A reference to the object is returned. See here: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
This answer is wrong, please see the comments below.
Document.getElementById() and methods or wrappers that rely on it return a reference.
Likewise for Document.querySelector().
This all stems from the DOM4 spec, which states that (emphasis mine):
A collection is an object that represents a lists of DOM nodes. A collection can be either live or static. Unless otherwise stated, a collection must be live.
From a programming point of view this notion is easy to understand, you waste less memory and no time is spent copying things around, leading to faster execution.
However, for Document.querySelectorAll() we have an interesting case:
The NodeList object returned by the querySelectorAll() method must be static.
This means, as MDN puts it, that Document.querySelectorAll()
Returns a non-live NodeList of all the matching element nodes.
This means that the returned set is not a set of references to the original nodes, but instead to a set of nodes that represent the nodes at the time the query was executed. This means that a copy of all the matching nodes had to be made and you're no longer working with references to the live nodes.
In short:
Some JavaScript methods return references to the DOM Node.
Some JavaScript methods return array-like objects that contain references to the DOM Nodes. These objects aren't very big(?).
jQuery returns a jQuery object that contains references to the DOM Node(s). These jQuery objects could get quite big, depending on how many chained calls are made.
The actual DOM nodes are never actually returned "by value".
The size of the references themselves are small. Typically the size of a pointer.
JavaScript:
getElementById and querySelector(?) return references to the DOM Node.
getElementsByClassName and getElementsByTagName return live HTMLCollections.
getElementsByName returns a live NodeList.
getElementsByNameNS returns a live NodeList or a live HTMLCollection, depending on the browser.
querySelectorAll returns a non-live NodeList.
HTMLCollection and NodeList contain references to DOM nodes. They don't seem to be very big objects.
Live vs. Non-Live
From MDN:
In some cases, the NodeList is a live collection, which means that
changes in the DOM are reflected in the collection. For example,
Node.childNodes is live:
var parent = document.getElementById('parent');
var child_nodes = parent.childNodes;
console.log(child_nodes.length); // let's assume "2"
parent.appendChild(document.createElement('div'));
console.log(child_nodes.length); // should output "3"
In other cases,
the NodeList is a static collection, meaning any subsequent change in
the DOM does not affect the content of the collection.
document.querySelectorAll returns a static NodeList.
jQuery
From learn.jquery.com
A jQuery object is an array-like wrapper around one or more DOM elements. To get a reference to the actual DOM elements (instead of the jQuery object), you have two options. The first (and fastest) method is to use array notation:
$( "#foo" )[ 0 ]; // Equivalent to document.getElementById( "foo" )
The second method is to use the .get() function:
$( "#foo" ).get( 0 ); // Identical to above, only slower.
You can also call .get() without any arguments to retrieve a true array of DOM elements.
I am doing a tree view like by referring this link
I am getting this error in firebug
**Non-standard document.all property was used.
Use W3C standard document.getElementById() instead.
return document.all[id].style[property];**
How to use document.getElementById() at that place
This error message means that you accessed the property "all" of the variable document, but this property is, let's say, deprecated, so should not be used. The console says that you should use a method "getElementById", which returns the element with given id, on which you can then proceed.
To access the element by id if you know the id, you can for example, declare a variable and assign to it the result of getElementById (there is going to be a problem with style[property]):
var myElement=document.getElementById("id");
return myElement.property; // height for example
or just
return document.getElementById("id").property; // height for example