How to solve the "Cannot add class to undefined" Error? - javascript

I have a page that I am trying to remove an element of with this section of code
oldContainer = $('div.choose-location-options');
oldContainer.addClass('hidden');
I am using the $ selector because I read online and in this answer that $ is short for document.querySelector, this code is working fine.
During code review my colleagues have told me that they do not want us using the $ is not best practice because it looks like jquery. So I changed it to this.
oldContainer = document.querySelector('div.choose-location-options');
oldContainer.addClass('hidden');
However this code will return an error message saying that cannot add class to undefined
Running this code in the browser will also remove the oldContainer so I thought it was an issue with the page loading so I added an event listener to the code for a page load
window.addEventListener('load', (event) => {
oldContainer = $('div.choose-location-options');
oldContainer.addClass('hidden');
});
This also returns undefined So I know it is not a timing issue. Why is the shorthand $ working but not the document.querySelector?

Related

Laravel Mix Javascript undefined function onClick

I am using Laravels Mix feature with javascript and I am having a bit of trouble. I've made a new javascript file and included it in app.js, I've then done a function in this file. I want to call it from an onClick event however its giving me an error.
In cart.js I have an array that is adding all the products, and I also have this line of coded added.
<a onClick="removeProduct(${product["id"]})" class="btn-remove1">Remove</a>
Also in cart.js I have this function, that needs to be called on the onClick event.
function removeProduct(id) {
console.log(id);
}
However, It then gives me this error when trying to call removeProduct()
Uncaught ReferenceError: removeProduct is not defined at HTMLAnchorElement.onclick
So I'm not sure how to handle this, I guess I could use jQuery and wait for the object to be clicked and then get the id but just wondering if I can do it by onClick. Thanks for any help!
Edit:
Looking into this some more, Webpack is including Cart.js and in app.jss the function removeProduct() is there. Do I need to somehow call it like Cart.removeProduct() or something? (I've never used web pack/mix before)
I've found out with webpack you need to define it in the global scope. You can simply do that by adding this line of code.
window.removeProduct = removeProduct;
Clear your cache and then check or check that js file is included into your file or not.

How to fix Uncaught TypeError: Cannot read property 'children' of null

carousel.js:5 Uncaught TypeError: Cannot read property 'children' of null**
I got this error when I'm going to ad slider to the page.
here is the js code for the error.
const track = document.querySelector('.carousel_track');
const slides = Array.from(track.children);
const dotsNav = document.querySelector('.carousel_nav');
const dots = Array.from(dotsNav.children); //here
const slideWidth = slides[0].getBoundingClientRect().width;
slides[0].style.left = 0;
slides[1].style.left = slideWidth + 'px';
Can anyone give me a solution for this? I really appreciate your help.
Apparently the error throws here const dots = Array.from(dotsNav.children); //here , though the source of error is coming from previous line.
The error hints that the track is null, which can happen when the selector didn't return any value.
Without seeing your HTML code its not so clear whats the exact reason, but its obvious that the element with class carousel_nav doesn't exist in the DOM at the moment of execution of this code.
Steps to debug:
Do the console log after acquiring the track object.
const dots = document.querySelector('.carousel_nav');
console.log('Dots are: ', dots);
...
Then on the console of the browser check the value, its probably null.
Check if the class is written correctly on the HTML element, without typos and mistakes. You can even run the js directly on the browsers console to see if the code is actually fetching .carousel_nav
If when you run your js code in browser's console and it returns actual value instead of null, but on the page load it still returns null then it can mean the carousel is being initialized by 3rd party library after certain event, most probably document.ready, you have to as well listen to the document ready event and only after that execute your code.
Sometimes just waiting for the document ready is not enough, so check the documentation of the library that you use, it should have some callback where you can execute your code exactly after the carousel is being initialized.
Might be that the carouself library that you use, need an additional parameter to render dots, do you actually see the dots in the rendered dom?
If you need more hints, provide the library name youre using and also html
P.S.
Sorry I didn't see //here comment. But the debugging steps are the same

How to 'click' querySelectorAll

Reading the title you could think that it is easiest question ever, but it ain't so. Problem: I have to use the click() method on querySelectorAll. As I found in Google, it does have the method in the library, but once I wrote the next code I got an error:
const gsdCaseNewBtn = $("#someId")
const gsdCaseOldButton = document.querySelectorAll('input[value="SomeValue Case"]')
gsdCaseNewBtn.click(() => {
gsdCaseOldButton[0].click()
})
So, as you can see, I'm creating a new button and trying to attach to it the 'onclick' behavior of already existing button. Method click() doesn't work with the error ("this method does not exist on type ..."). I tried to resolve the issue with addEventListener, but I don't need to set the onclick behavior of the old button, I just have to get it. Do someone has the idea how to get this code work?
Requirements: gsdCaseOldButton can't be of jQuery type. gsdCaseNewBtn can be any type.
This should fix your code:
<script>
const gsdCaseNewBtn = document.querySelector("#someId")
const gsdCaseOldButton = document.querySelectorAll('input[value="SomeValue Case"]')
gsdCaseNewBtn.addEventListener('click', () => {
gsdCaseOldButton[0].click();
});
</script>
I tested this in localhost ( I did not have access to Jquery) so i am not certain what the cause of the problem was.
Please let me know if this fixed your code.

Very weird jQuery error

So I had code that was working properly on my site:
$("#usr").load("somepage.php",{var1:var1,var2:var2});
But ever since I changed some code in the navigation bar, jQuery has been acting really strangely. The first major problem was that this line:
var w = $(window).width();
returns the error: object [global] has no method "width()"
And that didn't seem to matter, as all elements on the page functioned with that error (as if it was still being executed, because elements were still being placed)...but then I came to the page that implemented the first line of code, and I ran into the following error:
Cannot call method "load()" of null
Sure enough, I checked the console, and $("#usr") returns null, but I can see the HTML line in the page with the inline id of usr.
This causes a problem because I need to load data from that page for the page to function properly. But it gets even stranger. I thought I would just try a plain post request and take the data and use document.getElementById("usr").innerHTML = ... as a substitute, but I get the following error from this line:
$.post("somepage.php",{var1:var1,var2:var2},function(data){
document.getElementById("usr").innerHTML = data;
});
Error:
Uncaught TypeError: Object function $(el){if(!el)return null;if(el.htmlElement)return Garbage.collect(el);if([window,document].contains(el))return el;var type=$type(el);if(type=='string'){el=document.getElementById(el);type=(el)?'element':false}if(type!='element')return null;if(el.htmlElement)return Garbage.collect(el);if(['object','embed'].contains(el.tagName.toLowerCase()))return el;$extend(el,Element.prototype);el.htmlElement=function(){};return Garbage.collect(el)} has no method 'post'
What the heck is going on with jQuery?
I'm importing 1.8.2 from googleapis
That sounds a lot like you're loading Prototype or MooTools or something as well as jQuery, and so Prototype/MooTools/whatever is taking over the $ symbol.
If that's what's going on, and you need the other library, you can use jQuery.noConflict(). Then you either use the symbol jQuery instead of $ for your jQuery stuff, or you put all of your jQuery code into a function that you pass into jQuery.noConflict and accept $ as an argument, like so:
// Out here, $ !== jQuery
jQuery.noConflict(function($) {
// In here, $ === jQuery
});
Or you can just do it yourself:
// Out here, $ !== jQuery
jQuery.noConflict();
(function($) {
// In here, $ === jQuery
})(jQuery);
ready also passes the jQuery object into the function, if you're already using ready.

Rails Uncaught ReferenceError: $$ is not defined upgrading to jquery

Hey all looking throughout all of stackoverflow this looks like a common error i just cant wrap my head around. i am busy upgrading our site from pure JS to jquery in preparation for us moving over to Rails 3.1 now i have this javascript:
:javascript
["Ownership", "Management", "EmploymentEquity", "SkillsDevelopment", "PreferentialProcurement", "EnterpriseDevelopment", "SocioeconomicDevelopment"].each(function(element) {
$$('.' + element).each(function(s) {
s.toggle();
});
});
so basically it is running trough an array of css classes and then toggling them. now when i run this with the jQuery lib i get an error that looks like this
Uncaught TypeError: Object Ownership,Management,EmploymentEquity,SkillsDevelopment,PreferentialProcurement,EnterpriseDevelopment,SocioeconomicDevelopment has no method 'each'
now i am just trying to test one element at a time to get the jQuery working at least this is what i have so far.
$("OwnershipHeader").click(function () {
$("Ownership").toggle("slow");
});
very simple so just when you click on the header it toggles its children. so when i enter that in the console it works just fine. until i click on the header of coarse:
Uncaught ReferenceError: $$ is not defined
this seems really simple and yet its breaking every time... i am relatively new to jQuery i have just worked with the Jquery UI lib before. any suggestions are appreciated
Uncaught TypeError: Object Ownership,Management,EmploymentEquity,SkillsDevelopment,PreferentialProcurement,EnterpriseDevelopment,SocioeconomicDevelopment has no method 'each'
I think you meant forEach. But since this doesn't work in all browsers, use jQuery's each function
$.each(["Ownership", "Management"], function(i, element) {...
Uncaught ReferenceError: $$ is not defined
jQuery uses a single dollar sign ($)
$("OwnershipHeader").click(function () {
$("Ownership").toggle("slow");
});
jQuery selectors are mostly like CSS selectors. So this should work:
$(".OwnershipHeader").click(function () {
$(".Ownership").toggle("slow");
});
Try this.
var array = ["Ownership", "Management", "EmploymentEquity", "SkillsDevelopment", "PreferentialProcurement", "EnterpriseDevelopment", "SocioeconomicDevelopment"];
$.each(array, function(i,element) {
$('.' + element).toggle();
});
It looks like it was coded previously with PrototypeJS, which provides $$ and [].each.
I'm not sure if .toggle is the same behavior in PrototypeJS and jQuery.
var col = ["Ownership", "Management", "EmploymentEquity", "SkillsDevelopment", "PreferentialProcurement", "EnterpriseDevelopment", "SocioeconomicDevelopment"];
$.each(col,function(i,e){
$('.'+e).each(function(j,s){
$(s).toggle();
});
})
*in jquery first of all there is no variable defined as $$ and only $ is defined.
*secondly each function is used as i have mentioned and the first variable passed to the function that is provided to each is the index in array and second variable is the actual element
look here for each and toggle documentation

Categories