is window.document.element a valid object? - javascript

Just as window and document objects in JS corresponds to window(?) and <body> elements in HTML, can you refer to more nested elements of the <body> simply by appending with dots(.)? (like window.document.p)
I haven't seen it anywhere but I don't know since I haven't seen it anywhere. It just seemed intuitive to me that nested elements in HTML be represented as nested objects in JavaScript instead of having to getElementByID but somehow this chain seems broken after window.document

Some nested elements can be accessed diretcly using
document.
, e.g.,
document.forms
, which is an array containing all forms on the page.
In general, however, you have either to traverse the dom tree using
element.children or element.childNodes
or access the element directly using methods like
document.getElementById()
document.querySelector()
an alike.

No that is not possible. You should just try it before you post.
You can access descendants of <body> by calling its getElementsByTagName method or the new querySelector and querySelectorAll methods.
You should check this documentation for more info - https://developer.mozilla.org/en/DOM/element

no, that isn't possible. but for some elements, there are special collections;
window.document.forms -> all form elements
window.document.images -> all image elements
window.frames -> all frame elements

Related

When in JS you need to identify element by array order?

Ok so I finally have a code example to show this!
if ($('#Snowsports-row')[0].classList.contains("hidden") == false) {
$('#snowsports-only').removeClass("hidden")
}
The code works ONLY as written above, i.e., if the [0] were moved to the second line and removed from the first line, or if it were present/absent in both lines, it would fail.
I understand the output difference...
$('#Snowsports-row')
=> [<div>...]
$('#Snowsports-row')[0]
=> <div>...
...but I'm not understanding under what circumstances you're OK to get an array of element(s) and in which you need to tease out the exact element.
THANKS FOR ALL ANSWERS! Very clearly helped me to figure out that the problem may have been confusing JS/jQuery methods. Final version:
if ($('#Snowsports-row').hasClass("hidden") == false) {
$('#snowsports-only').removeClass("hidden")
}
The .classList method is not widely supported (not in MSIE 9.0 for example) so it's not portable, although where it exists it's fast.
Since every ID in a document is supposed to be unique, and since calling removeClass for a class that isn't present is harmless, just replace your entire call with:
$('#Snowsports-row').removeClass('hidden')
Or better yet, if that class means what I think it does, use .hide() and let jQuery do its job for you, potentially animation the transition in the process.
Alternatively, if you actually wanted to stick with using DOM and classList, you should use the .remove() method that classList already supports:
document.getElementById('#Snowsports-row').classList.remove('hidden')
although there's a minor disadvantage in that this code will crash if that element isn't found (since .getElementById will return null) whereas jQuery silently ignores calls made on empty selectors.
As for the meta-question - you use [n] if you want to access the single DOM element at position n within the jQuery object, as you've done when you use .classList.
You use .eq(n) to obtain a jQuery object representing that DOM element, e.g. if you want to apply jQuery methods to that (single) element.
If there's only a single element, or you want the jQuery method to apply to every matching element, just call the method directly on the selector, as I've done above.
First off, by using jQuery for what it's good at, you can replace this:
if ($('#Snowsports-row')[0].classList.contains("hidden") == false) {
$('#snowsports-only').removeClass("hidden")
}
with this:
$('#Snowsports-row').removeClass("hidden");
Your first block of code does the following:
With $('#Snowsports-row'), make a jQuery object that contains all DOM elements that match the select '#Snowsports-row'.
Then reach into the jQuery object with [0] and get the first DOM object in that jQuery object.
Then, use a property/method on that DOM element to determine if a class exists on that DOM element with your .classList.contains("hidden") reference.
Then, if you find that class, remove it.
A jQuery object contains inside it an array of DOM elements. If you call a method on the jQuery object itself like:
$('.tableRows').html("hello");
Then, you are asking jQuery to operate on ALL the DOM elements inside the jQuery object. You must use jQuery methods, not DOM methods.
If, on the other hand, you want to use a method such as .classList.contains(), that is only a method on an actual DOM element. That isn't a jQuery method. So, you have to reach inside of the jQuery object to get a specific DOM element out of it. That's what the [0] does. It reaches into the jQuery object and gets the first DOM element from its internal data structure. Once you have that DOM element, you can then use any DOM element methods on that DOM object.
FYI, if you ever want to get just the first DOM element from a jQuery object, but want the result to be a jQuery object, not just a DOM element, instead of [0], you can use .eq(0) like ths:
$('#Snowsports-row').eq(0).removeClass("hidden");
Now, in this specific case, this is never necessary because $('#Snowsports-row') cannot ever contain more than one DOM element because internally jQuery will only return the first matching DOM element when you are searching for a ID value (since there's never supposed to be more than one matching element with the same ID).
Just keep in mind that DOM element and a jQuery object are completely different types of objects with different methods on them. What makes it slightly confusing is that a jQuery object contains an internal list of DOM elements. But, if the object you are operating on is a jQuery object, then you can only call jQuery methods on it. If you reach into the jQuery object and pull out a DOM element, then you can only call DOM methods on it.
First of all, ids must be unique, so if you have more than one #Snowsports-only elements you can experience problems.
In your question, you are mixing jQuery code with pure Javascript code.
This:
if ($('#Snowsports-row')[0].classList.contains("hidden") {
...
}
Means that you get the first instance of #Snowsports-row (remember that is better if there is only one element with this id), but you get the DOM object (pure javascript) with the jQuery selector. You can do the same thing in jQuery like this:
$('#Snowsports-row').hasClass("hidden")
See more:
https://api.jquery.com/hasclass/
https://developer.mozilla.org/es/docs/Web/API/Element/classList
Sure, because you are operating over a list. Now, you're kind of mistaking the jQuery/javascript code. If you would like to use the same line twice you can basically drop jQuery altogether and write something like this:
var el = document.getElementById('Snowsports-row');
if (el.classList.contains('hidden')){
el.classList.remove('hidden');
}
In the first line you're selecting one specific DOM element, whereas in the second line you are selecting ALL elements in the DOM that fit that selector and removing the "hidden" class from all of them. Basically checking whether the element has a class can only be performed over an element (that's why you need to select the index, specifying a given element), but jQuery allows you to remove the class of every element inside a list (hence your second line)
Use jQuery's .eq() function. So:
var el = $('#Snowsports-row').eq(0);
if (el.hasClass("hidden")) {
$(el.removeClass("hidden")
}
There's also no harm in calling removeClass on an element that might not have that class... so:
$('#Snowsports-row').eq(0).removeClass('hidden');

Javascript: Do properties of `document` include nodes beyond `body`?

I'm reading through Mozilla's Introduction to DOM, and found one of their examples interesting - where body appeared as a property of document. This was atypical to me because I had only seen examples of nodes being accessed using get.
I tried three different ways of accessing the body element of document,
document.body.appendChild(_someNode_)
document['body'].appendChild(_someNode_)
document.getElementsByTagName('body')[0].appendChild(_someNode_)
and found the example shown in Mozilla to be a nice shorthand (first line).
At this point, I felt that I could simply chain nodes with this shorthand, but found that it was undefined for anything but body.
Here's an example:
console.log(document.body); // #document
console.log(document.body.p); // undefined
console.log(document.body.getElementsByTagName('p')[0]); // <p></p>
What's going on here?
There are some tags that get their own properties in document, but they are rare, and in some cases are browser-dependent. An example would be document.forms that contains the collection of all form tags, and document.frames, that contains a collection of al frames and iframes contained by a page.
But you should avoid these properties, and use instead .getElementById(), .getElementsByTagName(), and the more recent and versatile .querySelector() and .querySelectorAll()
The Document object is special. It has a property called body that returns the <body> element, but in general you have to use getElementsByTagName() and its friends.

javascript alternative for jquery element addressing

What is Javascript alternative for this:
$('#clientDetailModal #heightValue')
I need it because in my code this works:
document.getElementById('heightValue').checkValidity()
but this doesn't:
$('#clientDetailModal #heightValue').checkValidity()
And I need to select only heightValue within clientDetailModal div.
Try $('#clientDetailModal #heightValue')[0].checkValidity()
The reason you need to do the [0] is, (as per the jquery id selector documentation)
Calling jQuery() (or $()) with an id selector as its argument will
return a jQuery object containing a collection of either zero or one
DOM element
Since you'll get a collection with 1 DOM element (assuming you don't have multiple ids), you need to then explicitly "select" that element using the [0].
You could use get to get the DOM element :
$('#clientDetailModal #heightValue').get(0).checkValidity()
Just to be sure, as your question might be a little ambiguous : only one element can have a given ID in HTML. So if your element is either absent or inside #clientDetailModal, then you could as well use
$('#heightValue').get(0).checkValidity()
It would also be faster. But in that case, there would be nothing wrong in using document.getElementById.
Since document.getElementById('heightValue').checkValidity() works, it means your function checkValidity() is attached on native DOM elements. This means, you can do:
$('#clientDetailModal #heightValue')[0].checkValidity()
Plus: If your HTML is valid with no duplicate IDs, you can simply do
$('#heightValue')[0].checkValidity()
Since the OP asked for a JavaScript alternative. On modern browsers,
document.querySelector ('#clientDetailModal #heightValue')
will return the element you are asking for.
The direct equivalent would be
document.querySelectorAll ('#clientDetailModal #heightValue')
which returns an array of elements matching the selector requested, do yrou will need to add the [0] as per the other answers.
I presume this is what you're looking for :
document.getElementById('clientDetailModal').getElementById('heightValue').checkValidity();

Can a DOM object be an index/key in Javascript array?

Would like to maintain a map/hash of DOM objects. Can they serve as key objects? If not, what are the alternatives, please? If there are better ways - kindly enlist them as well.
You can put anything as the key, but before actual use it is always converted to string, and that string is used as a key.
So, if you look at what domObject.toString() produces, you see it is not a good candidate. If all of your dom objects have an id, you could use that id.
If not, and you still desperately need a key based on DOM object, you probably could do with using, for example, _counter attribute with automatic counter in background putting new unique value in a DOM object if _counter is not yet present.
window already maintains all DOM objects as properties. Instead of putting your own keys for each 'DOM object' try to use window or document object and methods that uses index based on the layout of DOM tree.
No, because object keys are strings.
You'd have to "serialise" your objects by id or something, then perform a lookup later. Probably not worth it, depending on what your actual goal is here.
No, but you can set an attribute on the DOM element that contains a number, which you would have as the index in a numerically-indexed array.
Easiest is to set a data-attribute on the element instead.
Not exact. But I think you want something like below. You can do with jquery,
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. It operates on a jQuery object representing a set of form elements. The form elements can be of several types
Refer below link :
http://api.jquery.com/serializeArray/

Jquery returns a list using id selector

I'm having trouble with jquery and selectors using the following code:
<div id="test"></div>
console.log($('#test'));
This always returns a list like [<div id=​"test">​</div>​] instead of the single element.
This results on always having to write $('#test')[0] for every operations instead of only $('#test'). Any idea on why?
Regards
Jquery will not return the HtmlElement, it returns a jQuery object.
A jQuery object contains a collection
of Document Object Model (DOM)
elements that have been created from
an HTML string or selected from a
document. Since jQuery methods often
use CSS selectors to match elements
from a document, the set of elements
in a jQuery object is often called a
set of "matched elements" or "selected
elements"
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().
http://api.jquery.com/Types/#jQuery
This is an example of the Composite Design Pattern
The Composite Pattern describes a group of objects that can be treated in the same way a single instance of an object can. Implementing this pattern allows you to treat both individual objects and compositions in a uniform manner. In jQuery, when we're accessing or performing actions on a single DOM element or a group of DOM elements, we can treat both in a uniform manner. http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjquery
jQuery encapsulates any objects found for a number of reasons. For one, it ensures that no matter what, null will never be returned for example. Rather, the elements found are inserted into a list. The fact that even though you're searching for a single element, the mechanism always remains the same and therefore the results will be placed into an array of one element rather than the element itself.
In jQuery it is better to think of selectors as matching multiple items, and your solution would be best if you use the each syntax to iterate through the matches items...
$('#test').each(function() {
console.log($(this));
});
As ID is not unique, jQuery looks for every element with such ID. So it's always returns a list, because threre is no guarantee that the element is exactly one

Categories