includes() not working in all browsers

Christian4423 picture Christian4423 · Jul 10, 2015 · Viewed 103.4k times · Source

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.

Answer

Tushar picture Tushar · Jul 10, 2015

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;
    };
}