JScript Check if element exists and remove it - javascript

I'm trying to write a simple function in javascript to check if an element exists in the DOM and if it does remove, and if it doesn't, append it to the page, so far i've got this
if document.contains(document.getElementById("submitbutton") {
document.getElementById("submitbutton").remove();
} else {
lastDiv.appendChild(submitButton);
}
(lastDiv is just the div I want to append the div 'submitButton' to)
Yet i'm getting the error "Uncaught ReferenceError: myFunction is not defined"
Any help?
I'm aware this is a very newbie question, sorry about that

There is a syntax error in the code, if statements require parens
if (document.contains(document.getElementById("submitbutton"))) {
document.getElementById("submitbutton").remove();
} else {
lastDiv.appendChild(submitButton);
}

Check if element exists:
function removeID(_id ){
var e=document.getElementById(_id);
if(e!==null) e.remove();
}
removeID( "myElement" );

Related

I am encountering some errors while doing the JavaScript implementation on my little project, Calculator. Can you help me, guys?

Here is the error message
Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
This is the code
let equal = document.querySelector(".btn-equal");
equal.addEventListener("click", function (e) {
if (screen.value === "") {
screen.value = "";
} else {
let answer = eval(screen.value);
screen.value = answer;
}
});
Btw, I am a beginner on coding
I hope that I can make it work
Thank you
The error is caused by document.querySelector('.btn-equal'); not finding any elements, which means that equal is null, and so equal.addEventListener() is calling a method on an object that doesn't exist.
Most likely you are either calling document.querySelector() before the document has finished loading, or the element you want to select is not being identified properly. To debug this issue you can run console.log(document.querySelector('.some-other-element')) and see if you are able to fetch any parts of the page or not.

Magento 2 error in swatchRenderer.js

I have overridden magento SwatchRenderer.js file in app\code\Mydirectory\CustomSwatches\view\frontend\web\js\SwatchRenderer.js.
My problem is I get an error in my product page load:
Uncaught TypeError: Cannot read property 'updateData' of undefined
I found out that data('gallery') on SwatchRenderer.js's following function is undefined.
updateBaseImage: function (images, context, isProductViewExist) {
var justAnImage = images[0];
if (isProductViewExist) {
context
.find('[data-gallery-role=gallery-placeholder]')
.data('gallery')
.updateData(images);
} else if (justAnImage && justAnImage.img) {
context.find('.product-image-photo').attr('src', justAnImage.img);
}
}
I checked a Magento 2 demo site. On that site the above data attribute is set as a JavaScript object. The target element is a div with the above attribute. But in my site it is undefined and obviously I think that data attribute is not set on my site. Can anyone help me to find the setter function/view/file for above element? Any help would be appreciated. Thanks.
What theme was used in your Magento instance? Did you rename the container class names?
One interesting piece of code is found on line 202 of the SwatchRenderer.js file. Under the _create function you will find the initialization of the gallery variable as seen here
You will notice that it finds the element with the data-gallery under the .column.main element. Thus, as missing column main element would return an empty response.
I found a pretty efficient way to fix this:
Copy the /vendor/magento/module-swatches/view/frontend/web/js/swatch-renderer.js-file to app/design/YourName/YourTheme/Magento_Swatches/web/js/swatch-renderer.js and replace the code inside updateBaseImage() (line ~1152) with the following:
updateBaseImage: function (images, context, isInProductView, eventName) {
var gallery = context.find(this.options.mediaGallerySelector).data('gallery');
if (eventName === undefined && gallery !== undefined) {
this.processUpdateBaseImage(images, context, isInProductView, gallery);
} else {
context.find(this.options.mediaGallerySelector).on('gallery:loaded', function (loadedGallery) {
loadedGallery = context.find(this.options.mediaGallerySelector).data('gallery');
this.processUpdateBaseImage(images, context, isInProductView, loadedGallery);
}.bind(this));
}
},
The trick is: this method doesn't wait for the gallery to be fully loaded, while this event (gallery:loaded) is readily available. By adding this to the method, it works fine.
I just hope that the Magento Dev's pick up on this and implement this in the core-code.

Uncaught TypeError: Cannot read property 'innerHTML' of null

Keep getting this error, no idea why
Uncaught TypeError: Cannot read property 'innerHTML' of null
My code is:
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
function calculateCircumference (diameter) {
return diameter * 3.14;
}
write (calculateCircumference(4));
Admittedly, the error message is not exactly transparent as to its meaning (but at least you get an error - jQuery would just silently do nothing!)
What it means is that the result of document.getElementById('message') is null. Looking at the docs you will find that this happens when the element cannot be found.
The main reason for an element not being found is because it doesn't exist yet.
<script>// do something with document.getElementById('message');</script>
<div id="message"></div>
The above will FAIL because message does not exist yet. Moving the script after the div will make it work.
Side-note: 3.14 is far too inaccurate. Use Math.PI instead, it's as accurate as a number in JavaScript can be.
Seems that your code is executed before the DOM is ready
window.onload = function(){
function write(message) {
document.getElementById('message').innerHTML += message + '<br/>';
}
function calculateCircumference (diameter) {
return diameter * 3.14;
}
write (calculateCircumference(4));
}
If you have your id is set and you still get the same error, make sure you have done the opening and closing tags of your html correctly.
This error is usually caused when the element is not loaded and the js function is trying to access it.
try adding the <script> tag at the very end of the document before </body>
or check if the name of the element is mistyped.

TypeError: $(...) is null - how to use noconflict()

i get error TypeError: $(...) is null.
<script>
$('w_pages').observe('change', function(){
parent.preview.location = 'W/preview/<?=$page['parent_id'] ?>/?p='+$('w_pages').value;
});
$('w_layout').observe('click', function(){
parent.preview.Tiny.showURL('S/layout/'+$('w_pages').value+'?ajax=true',true)
});
</script>
i read that it is because of a conflict. how do i wrap this in noConflict()
There is no conflict here.
You are using the dollar function of Prototype, which returns a reference to the element with id equal to its argument. If no such element exists in the page it returns null, which in turn causes the TypeError.
I don't know why no such element exists in your page or how to make the JS work like it should, but you can avoid the immediate error by checking the return value before calling methods on it:
var wPages = $('w_pages');
if (wPages) {
wPages.observe('change', function(){
parent.preview.location =
'W/preview/<?=$page['parent_id'] ?>/?p='+wPages.value;
});
}
// The same for w_layout
i fixed it. i was indeed missing the element. thanx for putting me in the right direction.

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

I'm teaching myself AJAX to AJAXify my site. In my template, I have the following JS code to get some JSON data from a view then append the data to a div.
function filter(type) {
$.getJSON(
'/activity_stream/global-activity-stream/',
{xhr: "true", filter: type},
function(data) {
$('.mainContent').children().remove();
$(data).appendTo('.mainContent');
});
}
$(".btn").click(function () {
filter("recent");
});
}
I think my view is returning proper JSON but now data is not being added to the .mainContent div.
It gives this error:
Uncaught TypeError: Cannot read property 'ownerDocument' of undefined.
Make sure you're passing a selector to jQuery, not some form of data:
$( '.my-selector' )
not:
$( [ 'my-data' ] )
I had a similar issue.
I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.
The same issue came up for me inside of $elms.each().
Because:
the function you pass to .each(Function) exposes (at least) two arguments; the first being the index and the second being the element in the current element in the list, and
because other similar looping methods give current the element in the array before the index
you may be tempted to do this:
$elms.each((item) => $(item).addClass('wrong'));
When this is what you need:
$elms.each((index, item) => $(item).addClass('wrong'));
In case you are appending to the DOM, make sure the content is compatible:
modal.find ('div.modal-body').append (content) // check content
If you use ES6 anon functions, it will conflict with $(this)
This works:
$('.dna-list').on('click', '.card', function(e) {
console.log($(this));
});
This doesn't work:
$('.dna-list').on('click', '.card', (e) => {
console.log($(this));
});
In my case, this error happened because my HTML had a trailing linebreak.
var myHtml = '<p>\
This should work.\
But does not.\
</p>\
';
jQuery('.something').append(myHtml); // this causes the error
To avoid the error, you just need to trim the HTML.
jQuery('.something').append(jQuery.trim(myHtml)); // this works

Categories