This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 8 years ago.
I've always had to use a selector to get elements in the DOM so I could retrieve the data that I need. eg:
var test1 = document.getElementById('testElement').value; // or
var test2 = document.querySelector('#testElement').value; // or
var test3 = $('#testElement').val(); // etc...
Recently, I noticed that I no longer need to do that. Instead, simply using the element's id seems to be sufficient. It seems to be used as a reference to the element. The code below works for me in Chrome, Firefox and even IE9.
var test4 = testElement.value;
I've been trying to find some more information on this but wherever I look, everyone says that selectors need to be used.
So either my colleagues and I completely missed this somehow, or not many people know about this. Or, I suppose, I'm horrible at searching for information.
Basically, I'm looking for more information on this.
So please point me in the right direction so I can investigate further and make sure this functionality is here to stay and can be used consistently.
This is a browser feature, which is not according to the specification. This means that for your code to work on most browsers, it should be using some selector. Also, testElement may not work if it already is a global variable.
Depending on the browser the element id may be in the global scope. That is a nice feature and all but I would not depend on this for your applications. If you want to be thorough I suggest using getElementById() or a selector with jQuery.
Related
This question already has answers here:
What is the difference between 'remove' and 'removeChild' method in JavaScript?
(2 answers)
Closed 2 years ago.
I am developing a website. There are a lot of spots, where I have to remove the html element. The previous, main contributor used to do it like this:
var elem = document.getElementById('element');
elem.parentNode.removeChild(elem);
I'm wondering why didn't he just use
elem.remove();
instead.
I've gotten to the point, where the first method didn't work and returned an error, but the second one worked perfectly. Of course I wanted to stick with the code standard in this project, so my first try was to use parentNode.removeChild. Unfortunatelly I cannot contact that person to ask why is it done like that.
What is the difference between these two and can I safely replace those?
As from MDN, the two are equivalent. The .remove() was inspired by jQuery and was implemented much later. IE does not support it.
If you don't need IE, you can safely replace parentNode.removeChild, but if you will transpile the code, the replace method have polyfill using parentNode.removeChild method...
Source of the answer
How is remove different from removeChild?
remove only needs a reference to the child. removeChild needs a reference both to the parent and the child. The result is identical.
Also you might think ,Is there any way to ensure that element is actually removed from memory?
No. You can only unreference it and hope that there is a garbage collector which will detect the object is not referenced and then will remove it.
This question already has an answer here:
Why sometimes jQuery selector returns something like "a.fn.init"? [closed]
(1 answer)
Closed 6 years ago.
I don't know what happen to my Chrome browser, but all of sudden the behavior of doing $('div#my') in console is totally different from before. One time I've experienced this but later it somehow recovered, so I don't know how to reproduce it, and today it happened again.
Please watch the video:http://peaceevertvimg.org/jq.php.
In the video I do $('div#my') in two different browsers:
the first browser is not chrome but I believe it imitates Chrome so its behavior is what I expect and what I have almost always been experienced. Because currently my chrome is not working as expected so I have to use it to demonstrate my expection: when you do $('div#my)` you see directly the html TAG, and you can easily see the tag's html content, which is "something" in this case.
In contrast, in my chrome browser, the result is different, when I do $('div#my') I see an Object(n.fn.init), and I can't see the "something" immediately, which of course is very inconvenient. But before, I am pretty sure it was not like this, the behavior WAS exactly like that in the first browser.
The simple webpage in this video is http://peaceevertvimg.org/jquery.php, you can go test for yourself in chrome browser. And I am pretty sure most of you will see the first behavior. What happened to my chrome?(I've disabled all expansions and updated it to the latest version)
By the way, is "HTML Tag" and "Object Reference" the right words to describe these two different outcome?
*************Update*************
If the video is not sufficient to understand what I ask and what I want to fix, these two pictures may help.
Picture#1: This is the "normal" behavior I've expected:
Picture#2: This is the current behavior I am experiencing:
You can see the big differences, the first one is much more intuitive, revealing key information immediately, while the 2nd one is not, at least to me. What causes this problem and how do I go back to the first one?
$('div#my') doesn't return a DOM reference. It returns a jQuery wrapper around the found elements.
$('div#my')[0] would return a DOM reference. Or, forget jQuery and use:
document.getElementById("my");
...and you will get a DOM reference directly
Also, since there should/will only ever be one element with a given ID, it is unnecessary to use div#my, just use #my.
Assuming we have a <div id=someDiv>, and then we write:
console.log($("#someDiv"));
console.log($("#someDiv")[0]);
Chrome shows this:
In the first log, we see that the result is a jQuery object that contains one element (the div). In the second, we see the element directly.
Now, depending on what version of Chrome you have, you may see the first one reported simply as [Object object], but that doesn't change the underlying result.
From: Devx (http://www.devx.com/codemag/Article/40923)
Selectors let you select DOM elements so that you can apply
functionality to them with jQuery's operational methods. jQuery uses a
CSS 3.0 syntax (plus some extensions) to select single or multiple
elements in a document. You're probably already familiar with the CSS
syntax from HTML styling. Even if you're not, it's fairly easy to pick
up the key CSS selector features. I'll go as far as saying that jQuery
is the reason I really started to grok CSS. Using CSS syntax you can
select elements by ID, CSS class, attribute filters, or by their
relationship to other elements. You can even chain filter conditions
together. Look at this simple example, which selects all second-column
TD elements in a table using a simple selector: $("#gdEntries
td:nth-child(2)").
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. - See more at:
http://www.devx.com/codemag/Article/40923#sthash.l8Mo8CbH.dpuf
What you are seeing is said jQuery object returned by jQuery.fn.init().
What is going on is that jQuery() is being defined as jQuery.fn.init() which is another way to say jQuery.prototype.init() which is the selector function! What this means is that no one would call jQuery.fn.init() or jQuery.init() because jQuery() IS .init().
Some more info and a look at the jQuery code here: Help understanding jQuery's jQuery.fn.init Why is init in fn
As for a solution to your problem: https://chrome.google.com/webstore/detail/jquery-console-fix/jlmkkpkcgomkdpfhgjlpaaonhafnjgob?hl=en
In my company, some of the code accesses html elements purely by id, rather than document.getElementById or jQuery $("#id"). For example, if there is a select with an id of test they then use alert(test.selectedIndex) in the javascript and this works.
This breaks my model of how elements can be found / accessed in the DOM and I would have expected the alert to say that test was undefined. However, this works (and I have set up a fiddle to double check this). Can anyone please explain why elements can be accessed by their id, without any need for a getElementById / jQuery selector?
Many thanks.
See http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object (noting that 'globals' in javascript are just looked up from properties on the window object, so window[id] is exactly the same as just id, if id is not defined as a local variable)
This was previously non-standard behaviour, added by IE, that has now become part of the HTML5 spec.
In general I wouldn't recommend relying on it though because, as you've noticed, it can be quite confusing.
I'm working on a Firefox extension, in that I have a node which I want to know that whether the node belongs to the html (I mean the node belongs to document.body elements like div, p, etc) or just the window like menu, toolbar, etc.
Is there a way to do it in JavaScript?
Sorry if it's a stupid question, since I'm new to JavaScript. Let me know if there's something unclear or ambiguous.
I'm very thankful for your responses. :)
The simplest way I know of is to follow the parent chain and see if you find document.documentElement or not.
In jQuery, you can use jQuery.contains(document.documentElement, el)
In YUI3, you can use node.inDoc()
Curiously, both the jQuery and YUI implementations don't just follow the parent chain - they check for the existence of the .contains(el) or .compareDocumentPosition(el) methods on the desired ancestor and use whichever of those is present.
This question already has answers here:
Firing event on DOM attribute change
(6 answers)
Closed 5 years ago.
<div class="current"></div>
text
How do I detect when e.g. a .live class is added to this <div> and do something when it happened?
For example, if class is changed, then hide the link.
I have a minified script that makes changes on the <div>'s class. It’s too big for me to find the place where it happens, so I'm searching for some way to catch the class change.
There are DOM events, but they are far from perfect and not available in most browsers. In other words: Not possible (reliably). There are hacks like intervals and checking it in each iteration, but if you need to do something like this, your design is probably screwed. Keep in mind that such things will be slow and that there will always be a delay. The smaller the delay, the slower the application. Do not do that.
You may checkout the following article for some ideas.
I don't know if the class you add to the link is always the same but if so, why don't you use CSS for this.
<style type='text/css>
.myaddedclass{display:none}
</style>
If you just need to figure this out once (i.e. not in code), Google Chrome’s web inspector shows DOM changes live. Not sure if that’d help your situation out though.