right here is a block of my code. It works perfect in fireFox and Chrome. But not in IE. I get the error "Object doesn't support property or method 'includes'
"
function rightTreeSwapfunc2() { if ($(".right-tree").css("background-image").includes("stage1") == true) { $(".right-tree").css({ backgroundImage: "url(/plant-breeding/img/scenes/plant-breeding/stage5.jpg)" }) } else { $(".right-tree").css({ backgroundImage: "url(/plant-breeding/img/scenes/plant-breeding/stage3.jpg)" }) } }
I could change it up a bit and use vanilla JS and do:
document.getElementById("right-tree").classList.contains
But I would rather see if there is a way to get it to work in IE before changing the JS and editing the HTML and CSS.
indexOf() The Array#indexOf() function is a common alternative to includes() . The indexOf() function returns the first index in the array at which it found valueToFind , or -1 otherwise.
includes was not supported in IE. I had to write substitute of this function. This function basically did 2 things: check if element is in array.
includes() used as a generic methodincludes() method is intentionally generic. It does not require this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates includes() method called on the function's arguments object.
In JavaScript, includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false.
If you look at the documentation of includes()
, most of the browsers don't support this property.
You can use widely supported indexOf()
after converting the property to string using toString()
:
if ($(".right-tree").css("background-image").indexOf("stage1") > -1) { // ^^^^^^^^^^^^^^^^^^^^^^
You can also use the polyfill from MDN.
if (!String.prototype.includes) { String.prototype.includes = function() { 'use strict'; return String.prototype.indexOf.apply(this, arguments) !== -1; }; }
IE11 does implement String.prototype.includes so why not using the official Polyfill?
Source: polyfill source
if (!String.prototype.includes) { String.prototype.includes = function(search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > this.length) { return false; } else { return this.indexOf(search, start) !== -1; } }; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With