I have a simple code where I'm using Modernizr.js which can help me to detect if .webp is supported in the user's browser.
I'm using this code in <head> section which can guarantee to me loading before other scripts.
I have 2 same html elements and one of them is using .webp in background second one .jpg.
Now I need to modernizr.js will detect if .webp is detected and hide an element with .jpg background. And toggle it.
For now my Javascript is not removing html element with webp background when webp is not supported.
Is there any solution how to fix it or am I using it correctly?
MY CODE:
Modernizr.on('webp', function(result) {
if (result) {
document.getElementsByClassName("no-webp").remove();
} else {
document.getElementsByClassName("webp").remove();
}
});
section {
height: 200px;
width: 200px;
}
section.webp {
background: url('http://superweb.online/assets/img/mainbg.webp') no-repeat;
background-size: cover;
}
section.no-webp {
background: url('http://superweb.online/assets/img/mainbg.jpg') no-repeat;
background-size: cover;
}
<script src="http://superweb.online/assets/js/modernizr-custom.js"></script>
<section class="webp"></section>
<section class="no-webp"></section>
Your code:
is not removing element of class
no-webpbecause the return value ofgetElementsByClassNamemethod is (docs citation):so, you have to decide which one of them should be removed i.e.
document.getElementsByClassName("no-webp")[0].remove(); //note the 0 index.