appendChild method not working - javascript

Actually, it seems to work in JSFiddle without much problem.
https://jsfiddle.net/3zjqwbgy/5/
However, when I try to run it locally using Notepad++, I get the following error:
Cannot read property 'appendChild' of null
What could be the reason for this? How can I make it work locally?

Make sure you have the HTML available when you run the appendChild method.
That means you'll wrap everything into an load handler:
window.addEventListener("load", function () {
/* your actual code */
...
showElmntProperty("myDeck", "cardName", "first");
});
It's working in JSFiddle because JSFiddle is doing that for you automagically (by default)–you can change it, though:

Since your code works on JSFiddle, the only thing I can think of off the top of my head is you've misplaced your <script></script> tags. Try moving them down below the Table, so that they can be "seen" by JavaScript.

Whenever you get a "Cannot read property "some property name" of null, it simply means that the object that you are calling the method on doesn't actually refer to the object you think it is - it's not pointing to any object at all.
Now, in your code, you didn't say where (exactly) you are getting the error, but take these two lines:
node.appendChild(textnode);
document.getElementById(id).appendChild(node);
If you are getting the error on the first line, then the node variable does not, in fact, refer to anything. If it's the second line you are getting the error on, then document.getElementById(id) isn't returning an actual object, in which case, you'd need to check to see that the id variable you are using there actually matches an id of an HTML element.
And, of course, knowing when your code runs is vital. It may be that:
document.getElementById(id)
Is attempting to locate an element before that element has been parsed into the DOM.

Related

Remove Error From Checking If Element Exists As A Child Of Another In Javascript

My goal is to check if an element exists, but not just that, the element is.. well let me show you: if(document.getElementsByClassName("outerBox").getElementsByClassName("innerBox")) {//some code}. Now the problem is that if outerBox doesnt exist, it gives me this error message in the console: Uncaught TypeError: Cannot read property 'getElementsByClassName' of undefined.
I do not care weather the outerBox exists if it doesn't have the innerBox as a child, and also I do not care if the innerBox exsists outside of the outerBox. They have to be child and parent to eachother.
The code works, but I would like to get rid of the error, for a cleaner expirience, and because it isn't a good practise to leave errors displaying around like that, specially because you can't really use the console while this error is going, because the code is run every 100 milliseconds, so it just spams the console like crazy.
Now jsut one last thing, I can't use any outside library like jQuery, only vanilla Javascript.
Just use querySelector instead:
if (document.querySelector('.outerBox > .innerBox')) {
// then an innerBox exists as a direct child of an outerBox
}

jquery selector with variable does not find element

I have this line of code
$("#ir-area-name").html(list);
That works just fine, but I need to move this into a function that can be called for any id, and every answer I have seen says I can run it like this:
$("#"+variable_name).html(list);
where variable_name is a string containing the id. But, this isn't working for me, it doesnt find any element and no error message is printed. When printing the contents of the selector to console they both print the value [object Object]. However, when running it with the variable the element dissapears from screen (as it apparently didn't find the element so it never ran html()). For testing purposes I tried it like this as well:
$("#"+"ir-area-name").html(list);
But this still didn't find the element. So the question is how can I use a variable in a jquery selector (using jquery 1.7.1, testing on firefox).
You should use string concatenation.
$("#" + ir-area-name).html(list)
Or using ES6 string substitution syntax (docs)
$(`#${ir-area-name}`).html(list)
If the element is found, the html of the element will be replaced with the contents of list.

Javascript 'undefined is not a function' - can you clarify this example?

The relevant HTML:
<div id="suggestedEmailDiv">
Did you mean <a class="suggestedEmailClass">
<span id="suggestedEmailAddressSpan" class="address"></span>
#
<span id="suggestedEmailDomainSpan" class="domain"></span>
</a>?
</div>
The relevant javascript:
console.log("suggestion.address ", suggestion.address);
console.log("suggestedEmailAddressSpan ", $('suggestedEmailAddressSpan'));
// here's where it goes wonky:
$('suggestedEmailAddressSpan').text(suggestion.address);
The relevant Logs:
[Log] suggestion.address qwew (btadmin, line 195) <-- suggestion.address has a value
[Log] suggestedEmailAddressSpan (btadmin, line 198) <-- it is a defined span!!
<span id=​"suggestedEmailAddressSpan" class=​"address">​</span>​
[Error] TypeError: undefined is not a function (evaluating '$('suggestedEmailAddressSpan').text(suggestion.address)')
suggested (btadmin, line 205)
responder (prototype.js, line 5597)
I know I am missing something simple but important here... What is it??
Thanks for any help!!
Ok, the closest thing I can think of is that jQuery is not loaded.
What gave it away is that your log didn't return a jQuery object. jQuery returns an array-like object, which on the console appears like a bracketed list of elements. You can verify this by doing $('body') on the console in this StackOverflow page (because SO uses jQuery :P) and you should see something like:
[<body class=​"question-page new-topbar">​…​</body>​]
Now two things may have resulted when jQuery is not loaded:
$ is undefined, resulting in that error.
Some browsers (like Chrome) natively have a $ function which maps to document.querySelector. If jQuery didn't load, the $ global wasn't overridden. The error is because you called text() on the result of querySelector, which is the first DOM element that matches the provided selector.
Another possible situation is that something else has taken over the $ global. Symptoms may include jQuery successfully loaded but $ isn't jQuery. But your logs don't give much clues if this happened.
To solve your problem, make sure jQuery is loaded before your script. In addition, place scripts that operate on the DOM inside a callback to $(document).ready(), that way your scripts operate after the DOM has fully loaded.
In addition, your selector is wrong. ID's selectors start with #. However, providing wrong selectors to jQuery should not make the error since calling a wrong selector will return an empty jQuery set that will still have the .text() method.
you are missing the id selector in your query it should be like this
$("#suggestedEmailAddressSpan") read more about JQuery selector
for selecting Ids use
$('#suggestedEmailAddressSpan')
for class use
$('.suggestedEmailClass')
for jquery it's better to write your codes between ready function:
$(document).ready(function() {
//your code
});

unable to change body background color using javascript callback

I am learning to program in Javascript. I have created a jsfiddle here - http://jsfiddle.net/vvMRX/1/
function turnRed(node,f){
setTimeout(f,2000,[node]);
}
(function pageLoaded(){
turnRed(document.body,function(node){
alert(node);node.style.backgroundColor = '#ff0000';
});
})();
I am trying to use a setTimeout call on a function to change the body background color. I pass document.body as a node. In the callback, I change the node.style.backgroundColor but it does not work. Interestingly enough, using document.body.style.backgroundColor directly works. If I put an alert(node), it correctly identifies it as html bodyelement.
What am I missing here?
Appreciate responses.
Here's the following error that's being thrown in your JS:
Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
The reason for this is because in your setTimeout, you're passing node in an array. However, in your callback, you're accessing the node directly. Two ways of addressing this are:
Update your callback to access the node within the array.
(function pageLoaded(){
turnRed( document.body, function(node){
alert(node);
// Updated code below
node[0].style.backgroundColor = '#ff0000';
});
})();
The other way would be to update your setTimeout and pass node directly.
function turnRed(node,f){
setTimeout(f,2000,node);
}
Here's an updated fiddle: http://jsfiddle.net/vvMRX/3/
You mentioned that using document.body.style.backgroundColor worked - which makes sense - since document.body will point to the element that contains the content. For most pages, this is almost always the <body> element. However, for frameset documents, this would return the outer frame. (w3.org reference)
Finally, regarding the alert - what's up with that, right? You call alert(node), and it displays [object HTMLBodyElement], which means you were passing the correct element, right? (At least, that's what I would think too!)
What's actually happening is that alert is alerting the value of your array.
Here's a fiddle demonstrating that: http://jsfiddle.net/4Lf3J/
You should see three alerts.
In the first alert, I've updated the original alert to call node.constructor. Object.prototype.constructor will return a reference to the object that created the instance (MDN reference).
In this case, we'll see
function Array() { [native code] }
This hopefully will re-enforce the idea that you're passing an array.
The second alert is actually calling alert(document.body.constructor), which is what we EXPECTED to see originally. In this case, we see:
function HTMLBodyElement() { [native code] }
Finally, a third alert shows the values 1,2,3,4,5, which is just an alert of a simple array with those values (again, re-enforcing the idea that alerts will alert the value of an array - which is why you thought the alert was correct).
Hopefully this helps as you continuing learning JavaScript!
In your function turnRed you are passing node in an array. Try this:
function turnRed(node,f){
setTimeout(f,2000,node);
}
I tried this in the fiddle it works.
In this case i guess that you should use document.bgColor property directly
You can obtain more information and code samples here:
http://www.javascripter.net/faq/backgrou.htm
http://www.webcodingtech.com/javascript/change-background-color.php

jQuery "'events' is null or not an object" error, when using empty() or html()

I am getting the following error in IE:
'events' is null or not an object -- jquery-latest.js?d=1848173663, line 113 character 467
I am using jQuery 1.4.2, I'm not in a position to upgrade yet as we are on an older version of jQuery UI and have way too many bugs using anything newer than 1.4.2.
I get following error when I run this bit of code the second time:
$.post("page/view.do?undoCache=" + Math.random(), {
pageId: pId
}, function(xmlContent){
console.log('1');//get this one
$('#reloadCenterDiv').empty();
console.log('2');//don't get this one unless line above is commented out, then will run til next line
$('#reloadCenterDiv').html(xmlContent);
console.log('3');//don't get this
});
I'm pretty sure I'm not doing anything else to #reloadCenterDiv between calls.
Googling around for the error "'events' is null or not an object" I found this:
"Sounds like a reference to an event
handler is still there, when the
handler itself is already gone."
That sounds logical. Any other ideas of why and when this error would occur?
I have found where this is happening, but all clues for me end there.
How do I clean things up so I can call empty() or html() on #reloadCenterDiv again?
Here is the HTML for #reloadCenterDiv:
<div id="reloadCenterDiv" style="border:none; margin: 0; overflow:auto; overflow-y:scroll; height: auto;"></div>
Not sure, but it would seem like jQuery.cache is being overwritten.
Since a DOM element has (when necessary) a serial number that maps to jQuery.cache, when you run a function like .empty(), jQuery assumes the related data exists, looks up the data for that element, and deletes it.
In place of your first log, do this:
console.log(jQuery.cache);
And see what it gives you. I'll bet that something is overwriting it. Perhaps you're loading jQuery twice?
Here's an example that intentionally deletes jQuery.cache. It gives a similar error.
EDIT:
Summary of the comments below. During .empty() (or actually cleanData()) jQuery grabs the expando from all descendant elements in order to delete the associated data.
The issue is that when jQuery does so, it assumes that the data was successfully located. In this case, somehow the data is being disassociated from the element, so retrieving the data using the value of the expando is returning undefined.
Because jQuery doesn't (or didn't in 1.4.2) verify that data was found, its attempt to access the events property on the data is causing an error, because again data is undefined.
Updated versions of jQuery fix it with if ( data && data.events ) {, which verifies that there is some object against which to ask for its events property.
If you can't update your jQuery, you can set the HTML instead:
$("#divid").html("");
This is essentially doing the same thing.

Categories