What are the possible reasons for document.getElementById, $("#id") or any other DOM method / jQuery selector not finding the elements?
Example problems include:
jQuery silently failing to bind an event handler
jQuery "getter" methods (.val(), .html(), .text()) returning undefined
A standard DOM method returning null resulting in any of several errors:
Uncaught TypeError: Cannot set property '...' of null
Uncaught TypeError: Cannot set properties of null (setting '...')
Uncaught TypeError: Cannot read property '...' of null
Uncaught TypeError: Cannot read properties of null (reading '...')
The most common forms are:
Uncaught TypeError: Cannot set property 'onclick' of null
Uncaught TypeError: Cannot read property 'addEventListener' of null
Uncaught TypeError: Cannot read property 'style' of null
The element you were trying to find wasn’t in the DOM when your script ran.
The position of your DOM-reliant script can have a profound effect on its behavior. Browsers parse HTML documents from top to bottom. Elements are added to the DOM and scripts are (generally) executed as they're encountered. This means that order matters. Typically, scripts can't find elements that appear later in the markup because those elements have yet to be added to the DOM.
Consider the following markup; script #1 fails to find the <div> while script #2 succeeds:
<script>
console.log("script #1:", document.getElementById("test")); // null
</script>
<div id="test">test div</div>
<script>
console.log("script #2:", document.getElementById("test")); // <div id="test" ...
</script>
So, what should you do? You've got a few options:
Option 1: Move your script
Given what we've seen in the example above, an intuitive solution might be to simply move your script down the markup, past the elements you'd like to access. In fact, for a long time, placing scripts at the bottom of the page was considered a best practice for a variety of reasons. Organized in this fashion, the rest of the document would be parsed before executing your script:
<body>
<button id="test">click me</button>
<script>
document.getElementById("test").addEventListener("click", function() {
console.log("clicked:", this);
});
</script>
</body><!-- closing body tag -->
While this makes sense and is a solid option for legacy browsers, it's limited and there are more flexible, modern approaches available.
Option 2: The defer attribute
While we did say that scripts are, "(generally) executed as they're encountered," modern browsers allow you to specify a different behavior. If you're linking an external script, you can make use of the defer attribute.
[defer, a Boolean attribute,] is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
This means that you can place a script tagged with defer anywhere, even the <head>, and it should have access to the fully realized DOM.
<script src="https://gh-canon.github.io/misc-demos/log-test-click.js" defer></script>
<button id="test">click me</button>
Just keep in mind...
defer can only be used for external scripts, i.e.: those having a src attribute.
be aware of browser support, i.e.: buggy implementation in IE < 10
Option 3: Modules
Depending upon your requirements, you may be able to utilize JavaScript modules. Among other important distinctions from standard scripts (noted here), modules are deferred automatically and are not limited to external sources.
Set your script's type to module, e.g.:
<script type="module">
document.getElementById("test").addEventListener("click", function(e) {
console.log("clicked: ", this);
});
</script>
<button id="test">click me</button>
Option 4: Defer with event handling
Add a listener to an event that fires after your document has been parsed.
DOMContentLoaded event
DOMContentLoaded fires after the DOM has been completely constructed from the initial parse, without waiting for things like stylesheets or images to load.
<script>
document.addEventListener("DOMContentLoaded", function(e){
document.getElementById("test").addEventListener("click", function(e) {
console.log("clicked:", this);
});
});
</script>
<button id="test">click me</button>
Window: load event
The load event fires after DOMContentLoaded and additional resources like stylesheets and images have been loaded. For that reason, it fires later than desired for our purposes. Still, if you're considering older browsers like IE8, the support is nearly universal. Granted, you may want a polyfill for addEventListener().
<script>
window.addEventListener("load", function(e){
document.getElementById("test").addEventListener("click", function(e) {
console.log("clicked:", this);
});
});
</script>
<button id="test">click me</button>
jQuery's ready()
DOMContentLoaded and window:load each have their caveats. jQuery's ready() delivers a hybrid solution, using DOMContentLoaded when possible, failing over to window:load when necessary, and firing its callback immediately if the DOM is already complete.
You can pass your ready handler directly to jQuery as $(handler), e.g.:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script>
$(function() {
$("#test").click(function() {
console.log("clicked:", this);
});
});
</script>
<button id="test">click me</button>
Option 5: Event Delegation
Delegate the event handling to an ancestor of the target element.
When an element raises an event (provided that it's a bubbling event and nothing stops its propagation), each parent in that element's ancestry, all the way up to window, receives the event as well. That allows us to attach a handler to an existing element and sample events as they bubble up from its descendants... even from descendants added after the handler was attached. All we have to do is check the event to see whether it was raised by the desired element and, if so, run our code.
Typically, this pattern is reserved for elements that don't exist at load time or to avoid attaching a large number of duplicate handlers. For efficiency, select the nearest reliable ancestor of the target element rather than attaching it to the document.
Native JavaScript
<div id="ancestor"><!-- nearest ancestor available to our script -->
<script>
document.getElementById("ancestor").addEventListener("click", function(e) {
if (e.target.id === "descendant") {
console.log("clicked:", e.target);
}
});
</script>
<button id="descendant">click me</button>
</div>
jQuery's on()
jQuery makes this functionality available through on(). Given an event name, a selector for the desired descendant, and an event handler, it will resolve your delegated event handling and manage your this context:
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<div id="ancestor"><!-- nearest ancestor available to our script -->
<script>
$("#ancestor").on("click", "#descendant", function(e) {
console.log("clicked:", this);
});
</script>
<button id="descendant">click me</button>
</div>
Short and simple: Because the elements you are looking for do not exist in the document (yet).
For the remainder of this answer I will use getElementById for examples, but the same applies to getElementsByTagName, querySelector, and any other DOM method that selects elements.
Possible Reasons
There are three reasons why an element might not exist:
An element with the passed ID really does not exist in the document. You should double check that the ID you pass to getElementById really matches an ID of an existing element in the (generated) HTML and that you have not misspelled the ID (IDs are case-sensitive!).
If you're using getElementById, be sure you're only giving the ID of the element (e.g., document.getElemntById("the-id")). If you're using a method that accepts a CSS selector (like querySelector), be sure you're including the # before the ID to indicate you're looking for an ID (e.g., document.querySelector("#the-id")). You must not use the # with getElementById, and must use it with querySelector and similar. Also note that if the ID has characters in it that aren't valid in CSS identifiers (such as a .; id attributes containing . characters are poor practice, but valid), you have to escape those when using querySelector (document.querySelector("#the\\.id"))) but not when using getElementById (document.getElementById("the.id")).
The element does not exist at the moment you call getElementById.
The element isn't in the document you're querying even though you can see it on the page, because it's in an iframe (which is its own document). Elements in iframes aren't searched when you search the document that contains them.
If the problem is reason 3 (it's in an iframe or similar), you need to look through the document in the iframe, not the parent document, perhaps by getting the iframe element and using its contentDocument property to access its document (same-origin only). The rest of this answer addresses the first two reasons.
The second reason — it's not there yet — is quite common. Browsers parse and process the HTML from top to bottom. That means that any call to a DOM element which occurs before that DOM element appears in the HTML, will fail.
Consider the following example:
<script>
var element = document.getElementById('my_element');
</script>
<div id="my_element"></div>
The div appears after the script. At the moment the script is executed, the element does not exist yet and getElementById will return null.
jQuery
The same applies to all selectors with jQuery. jQuery won't find elements if you misspelled your selector or you are trying to select them before they actually exist.
An added twist is when jQuery is not found because you have loaded the script without protocol and are running from file system:
<script src="//somecdn.somewhere.com/jquery.min.js"></script>
this syntax is used to allow the script to load via HTTPS on a page with protocol https:// and to load the HTTP version on a page with protocol http://
It has the unfortunate side effect of attempting and failing to load file://somecdn.somewhere.com...
Solutions
Before you make a call to getElementById (or any DOM method for that matter), make sure the elements you want to access exist, i.e. the DOM is loaded.
This can be ensured by simply putting your JavaScript after the corresponding DOM element
<div id="my_element"></div>
<script>
var element = document.getElementById('my_element');
</script>
in which case you can also put the code just before the closing body tag (</body>) (all DOM elements will be available at the time the script is executed).
Other solutions include listening to the load [MDN] or DOMContentLoaded [MDN] events. In these cases it does not matter where in the document you place the JavaScript code, you just have to remember to put all DOM processing code in the event handlers.
Example:
window.onload = function() {
// process DOM elements here
};
// or
// does not work IE 8 and below
document.addEventListener('DOMContentLoaded', function() {
// process DOM elements here
});
Please see the articles at quirksmode.org for more information regarding event handling and browser differences.
jQuery
First make sure that jQuery is loaded properly. Use the browser's developer tools to find out whether the jQuery file was found and correct the URL if it wasn't (e.g. add the http: or https: scheme at the beginning, adjust the path, etc.)
Listening to the load/DOMContentLoaded events is exactly what jQuery is doing with .ready() [docs]. All your jQuery code that affects DOM element should be inside that event handler.
In fact, the jQuery tutorial explicitly states:
As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.
To do this, we register a ready event for the document.
$(document).ready(function() {
// do stuff when DOM is ready
});
Alternatively you can also use the shorthand syntax:
$(function() {
// do stuff when DOM is ready
});
Both are equivalent.
Reasons why id based selectors don't work
The element/DOM with id specified doesn't exist yet.
The element exists, but it is not registered in DOM [in case of HTML nodes appended dynamically from Ajax responses].
More than one element with the same id is present which is causing a conflict.
Solutions
Try to access the element after its declaration or alternatively use stuff like $(document).ready();
For elements coming from Ajax responses, use the .bind() method of jQuery. Older versions of jQuery had .live() for the same.
Use tools [for example, webdeveloper plugin for browsers] to find duplicate ids and remove them.
If the element you are trying to access is inside an iframe and you try to access it outside the context of the iframe this will also cause it to fail.
If you want to get an element in an iframe you can find out how here.
As #FelixKling pointed out, the most likely scenario is that the nodes you are looking for do not exist (yet).
However, modern development practices can often manipulate document elements outside of the document tree either with DocumentFragments or simply detaching/reattaching current elements directly. Such techniques may be used as part of JavaScript templating or to avoid excessive repaint/reflow operations while the elements in question are being heavily altered.
Similarly, the new "Shadow DOM" functionality being rolled out across modern browsers allows elements to be part of the document, but not query-able by document.getElementById and all of its sibling methods (querySelector, etc.). This is done to encapsulate functionality and specifically hide it.
Again, though, it is most likely that the element you are looking for simply is not (yet) in the document, and you should do as Felix suggests. However, you should also be aware that that is increasingly not the only reason that an element might be unfindable (either temporarily or permanently).
If script execution order is not the issue, another possible cause of the problem is that the element is not being selected properly:
getElementById requires the passed string to be the ID verbatim, and nothing else. If you prefix the passed string with a #, and the ID does not start with a #, nothing will be selected:
<div id="foo"></div>
// Error, selected element will be null:
document.getElementById('#foo')
// Fix:
document.getElementById('foo')
Similarly, for getElementsByClassName, don't prefix the passed string with a .:
<div class="bar"></div>
// Error, selected element will be undefined:
document.getElementsByClassName('.bar')[0]
// Fix:
document.getElementsByClassName('bar')[0]
With querySelector, querySelectorAll, and jQuery, to match an element with a particular class name, put a . directly before the class. Similarly, to match an element with a particular ID, put a # directly before the ID:
<div class="baz"></div>
// Error, selected element will be null:
document.querySelector('baz')
$('baz')
// Fix:
document.querySelector('.baz')
$('.baz')
The rules here are, in most cases, identical to those for CSS selectors, and can be seen in detail here.
To match an element which has two or more attributes (like two class names, or a class name and a data- attribute), put the selectors for each attribute next to each other in the selector string, without a space separating them (because a space indicates the descendant selector). For example, to select:
<div class="foo bar"></div>
use the query string .foo.bar. To select
<div class="foo" data-bar="someData"></div>
use the query string .foo[data-bar="someData"]. To select the <span> below:
<div class="parent">
<span data-username="bob"></span>
</div>
use div.parent > span[data-username="bob"].
Capitalization and spelling does matter for all of the above. If the capitalization is different, or the spelling is different, the element will not be selected:
<div class="result"></div>
// Error, selected element will be null:
document.querySelector('.results')
$('.Result')
// Fix:
document.querySelector('.result')
$('.result')
You also need to make sure the methods have the proper capitalization and spelling. Use one of:
$(selector)
document.querySelector
document.querySelectorAll
document.getElementsByClassName
document.getElementsByTagName
document.getElementById
Any other spelling or capitalization will not work. For example, document.getElementByClassName will throw an error.
Make sure you pass a string to these selector methods. If you pass something that isn't a string to querySelector, getElementById, etc, it almost certainly won't work.
If the HTML attributes on elements you want to select are surrounded by quotes, they must be plain straight quotes (either single or double); curly quotes like ‘ or ” will not work if you're trying to select by ID, class, or attribute.
I've tried to google my question but it makes me even more confused. My question is:
Here's the jQuery code:
$(document).ready(function() {
$(window).resize(function() {
if ($(this).width() < 200) {
$("p").css("color", "red");
} else {
$("p").css("color", "green");
}
});
}
Why do we write (this) and not ("this") ?
How do I know if (document) and (window) should be written with " " - and why's that?
Maybe you could link me somewhere that explains my issue. My code apparently works either way, I'm just curious about the why.
In JavaScript namespace, this is reserved [source].
The JavaScript object literal this refers to the inherited object from the present state in the current execution.
Another example of this we can see is when we are looping through an array and the object this would symbolize the current array object. You may, for example, see this.title, or this.description if we were iterating through a database array of blog posts.
this in jQuery refers to the inherited object. When we add the quotation marks, and it becomes a string, such as "this". This makes jQuery parse it as a DOM selector.
Then we are now looking for the HTML DOM selector <this>, which to my knowledge, does not actually exist in the accepted HTML syntax standards.
As otherwise stated, the concept of this will become tricky when you are working in other JavaScript environments, such as React or Angular. Within the context of a functional component, this becomes the state, such as handling user sessions.
I have the following construction in the template to check whether attributes are full
{{#if:{{{typeip|}}}|'''Type IP:'''{{{typeip}}}|<big>'''Type IP:'''</big><span style="color: red">not filled in</span>}}
I want the typyap attribute to be a property so that I can find it by semantic search or by using a query via the #ask function.
I tried the following construction
{{#if:[[typeip::{{{typeip|}}}]]|'''Type IP:'''{{{typeip}}}|<big>'''Type IP:'''</big><span style="color: red">not filled in</span>}}
But it doesn't work. The #asc function returns an empty request and the type ip property page is empty. Can you tell me what I'm doing wrong? I performed reindexing using a service script rebuildData.php But that doesn't help either. I tried to insert the property in various other places in the template, but it doesn't work either. The template is filled in using the form.
Thank you in advance!
Of course, it doesn't work. You invoke the {{#if:}} parser function incorrectly.
Its parametres are:
the condition,
the value returned if the first parametre does not evaluate to an empty string or whitespace,
the value returned if the first parametre is empty.
Therefore the semantic annotation should be in the second parametre, not the first:
{{#if:{{{typeip|}}}
| '''Type IP:''' [[typeip::{{{typeip}}}]]
| <big>'''Type IP:'''</big><span style="color: red">not filled in</span>
}}
{{{typeip}}} should be bare text without any wiki formatting. If you must pass wikitext to it to convert wikilinks into semantic annotations setting properties of the type Page, the simplest way will be as follows:
Install Scribunto,
create Module:Inject with the following content:
return {
property = function (frame)
local wikitext, property = frame.args[1], frame.args[2]
local annotation = mw.ustring.gsub (
wikitext,
'%[%[([^|%]]+)(|[^%]]*)?%]%]',
'[[' .. property .. '::%1%2]]'
)
return annotation
end
}
put the following in your template:
{{#invoke:Inject|property|{{{typeip|}}}|typeip}}
The template will convert any wikilinks in {{{typeip}}} like [[A]] or [[B|C]] into semantic annotations like [[typeip::A]] or [[typeip::B|C]].
Only in Mozilla Dev. Network is a function declaration explained with the following pseudoCode:
function name([param,[, param,[..., param]]]) {
[statements]
}
Is there any special significance or reason why the parameter list is represented as a nested list instead of just listing out the parameters as can be seen in any other function declaration on the Web?
Why not just show the declaration simply like:
function name(param1, param2, paramN...,) {
[statements]
}
Am I looking into this too much? Or is it just the Mozilla way of explaining the declaration?
The syntax shows when a parameter is optional
I have a problem I just can't solve, and need your advice since I'm out of ideas:
Context: I'm using tinyMCE Editor on my website and developed a custom plugin to include external xml files. So far everything works as expected. The links to the external xml files are represented as span-Tags:
<span id="-[XML Document 1]-" title="erg" class="xml_embed xml_include">-[XML Document 1]-</span>
but only in the tinyMCE editor with a custom class (xml_include) to distinguish them from normal text and upon switching to the html/source code view or saving, those span tags get replaced to xi:include elements:
<xi:include xmlns:xi="http://www.w3.org/TR/XInclude" show="xml_embed" href="erg">-[XML Document 1]-</xi:include>
The text that was set as innerHTML ("-XML Document 1]-") for the span tag(s) serves as placeholder in the editor and gets moved to the xi:include tag(s) in the source view and serves as placeholder there also.
Now to the problem:
The code to transform span.xml_include to xi:include gets called before the source code popup is displayed:
ed.onPreProcess.add(function(ed, o) {
var elm;
var domelm;
//get all span.xml_include elements
tinymce.each(ed.dom.select('span.xml_include', o.node), function(n) {
//IE ignores innerHTML when created with tinymce.dom, therefore use native JS createElement method to tell IE that custom tag is valid HTML
if(tinymce.isIE)
{
domelm = document.createElement('xi:include');
domelm.setAttribute("xmlns:xi", "http://www.w3.org/TR/XInclude");
domelm.href = n.title;
domelm.innerHTML = n.innerHTML;
domelm.show = n.className.split(/\s+/)[0];
document.body.appendChild(domelm);
ed.dom.replace(domelm, n);
}
else
{
//ed = tinyMCE.activeEditor
elm = ed.dom.create('xi:include', {href: n.title, show: n.className.split(/\s+/)[0]}, n.innerHTML);
elm.setAttribute("xmlns:xi", "http://www.w3.org/TR/XInclude");
ed.dom.replace(elm, n);
}
});
});
this code works perfectly fine in FF and Chrome, but not in IE (I tested 7 & 8): in IE the innerHTML of the new element "domelm" can't be set. Either it stays blank or if set explicitly an error is thrown. n.innerHTML can be accessed. I get an "Unknown runtime error" for the line domelm.innerHTML = n.innerHTML;
What else did I try?
the native JS way: domelm.appendChild(document.createTextNode(n.innerHTML)); to create a text node and append it to the "domelm" with no success (getting error: "unexpected call to method or property access", that should be the translation from "Unerwarteter Aufruf oder Zugriff" (german version))
the tinyMCE API way: tinymce.DOM.setHTML(domelm, n.innerHTML); resulted in no error but also the usual blank innerHTML
the jQuery way: $('#domelm').html(n.innerHTML); or first var jQelm = $(domelm); then jQelm.text(...); or jQelm.html(...); doesn't matter, neither works, IE always returns "unexpected call to method" error in the jquery core, which I obviously won't touch..
the tinyMCE way of creating elements as seen in the "else" part of the if condition above..if domelm.innerHTML = n.innerHTML; isn't explicitly set, elm.innerHTML just stays blank, else the same errors as on the approaches above occur, therefore I could as well skip the if(tinymce.isIE) detection..
What else can I do? Suggestions?
I also made sure to properly declare the custom xml namespaces, changed the MIME-type to application/xhtml+xml instead of simply text/html, "announced" the xi:include node for IE with document.createElement('xi:include'); and generally changed the code to please IE..and this seems to be the last major bug I have to overcome..
I'm not sure if it's an error in my code since FF and Chrome work fine local and remote and don't show any errors..?
Any help is appreciated, I hope I provided enough context for you so that it's clear what I meant. and sorry for mistakes, English is not my first language :)
Ok, wrapping the custom element in a p/div/span tag finally did the trick: I used span to leave the formatting unmodified..here is what I did:
In the "if(tinymce.isIE) part of the onPreProcess function, before "xi:include" is created, a wrapper is needed:
var wrapper = document.createElement('span');
Appending the custom tag-element to the wrapper:
wrapper.appendChild(domelm);
and appending a textNode to the wrapper since appending it to the domelm throws errors:
wrapper.appendChild(document.createTextNode(n.innerHTML));
and finally append the wrapper to the dom and replace the "span" tag (n) with the wrapped "xi:include" (wrapper, span tag to be modified):
document.body.appendChild(wrapper);
ed.dom.replace(wrapper, n);`
The result is a custom "xi:include" tag in IE with the correct innerHTML:
<span><xi:include xmlns:xi="http://www.w3.org/TR/XInclude" href="eh" show="xml_embed">-[XML Document]-</xi:include></span>