'How to get indexOf proper className of targeted element? [closed]

I have an target element which is a SVG which has two properties baseVal and aniVal, So I'm trying to get the proper indexOf the className from the SVG target element.

$('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;
    });
});


Solution 1:[1]

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 !== undefined) {
      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.)


Edit: modified check for the baseVaL property to !== undefined, because otherwise an empty baseVal would also make it go into the else branch.

Solution 2:[2]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 lost_in_magento