Home > Back-end >  Getting e.target.className.indexOf('close') is not function in Jquery
Getting e.target.className.indexOf('close') is not function in Jquery

Time:10-22

So i'm trying to conditionally check, where certain className has baseVal and other don't to check for indexOf

$('body').on('click', function (e) {
    if (e.target.className.baseVal && e.target.className.baseVal.indexOf('close') > -1) {
        return;
    } else if (e.target.className && e.target.className.indexOf('close') > -1)
        $(e.target).closest(".popover").remove();
    $('.popover').each(function () {
        whatever the code;
    });
});

CodePudding user response:

className on a "normal" HTML element is a plain string, only when you are dealing with an SVG target element, it will be an instance of SVGAnimatedString, which then has a baseVal property.

You tried to take that into account with your if/else already - but not entirely correctly. The value could still be an instance of SVGAnimatedString, but its baseVal might not contain close - in which case you go into the else branch, and there it tries to call indexOf on that SVGAnimatedString, which it does not posses.

You need to take your if condition apart into two separate checks here:

$('body').on('click', function (e) {
    if (e.target.className.baseVal) {
      if (e.target.className.baseVal.indexOf('close') > -1) {
        return;
      }
    } else if (e.target.className && e.target.className.indexOf('close') > -1)
        $(e.target).closest(".popover").remove();
        $('.popover').each(function () {
           //whatever the code;
        });
    }
});

(Whether that new "inner" if still needs an else branch, depends on what you want to happen when the target element is an SVG, but did not contain close.)

CodePudding user response:

Do you think this would help?

$('body').on('click', function (e) {
    if (e.target.classList.contains('close')) {
       $(e.target).closest(".popover").remove();
    }
    $('.popover').each(function () {
       // whatever the code;
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="close">Click 1 </button>
<button>Click 1 </button>
<button>Click 1 </button>
<button>Click 1 </button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related