Beginnerprogrammer Beginnerprogrammer - 6 months ago 12
Javascript Question

Remove a class which is not recognized by DOM

I am working on a interactive map, which triggers an overlay image (which highlights the selected area)

But now I add classes to an div and I want to delete them if I highlight an other area. First I tried the starts with indicator to remove classes which starts with

hl-
this is my js file:

$('.btn-pointer').click(function() {
$('.highlight-layer').removeClass('[class^="hl-"]');
});

$('.btn-sp').click(function() {
$('.highlight-layer').addClass('hl-sp');
$('.popover').not(this).popover('hide');
});

$('.btn-vp').click(function() {
$('.highlight-layer').addClass('hl-vp');
$('.popover').not(this).popover('hide');
});

$('.btn-sl').click(function() {
$('.highlight-layer').addClass('hl-sl');
$('.popover').not(this).popover('hide');
});

$('.btn-ec').click(function() {
$('.highlight-layer').addClass('hl-ec');
$('.popover').not(this).popover('hide');
});


and here is the html:

<section>
<div>
<img src="../img/map/map-full.jpg" alt="">
<button class="btn btn-sp btn-pointer" data-container="body" data-toggle="popover" data-placement="top" data-content="<h2>Safaripark</h2>">Safaripark</button>
<button class="btn btn-vp btn-pointer" data-container="body" data-toggle="popover" data-placement="top" data-content="<h2>Vakantiepark</h2>">Vakantiepark</button>
<button class="btn btn-sl btn-pointer" data-container="body" data-toggle="popover" data-placement="top" data-content="<h2>Speelland</h2>">Speelland</button>
<button class="btn btn-ec btn-pointer" data-container="body" data-toggle="popover" data-placement="top" data-content="<h2>Event Center</h2>">Event Center</button>
<div class="highlight-layer hl-ec"></div>
</div>




I tried to create a Fiddle but never added external Resources so the error it gives me is the following:
Uncaught Error: Bootstrap's JavaScript requires jQuery

Answer

You could use the callback for removeClass to filter out the classes you want to remove based on a starting string etc

$('.highlight-layer').removeClass(function(i, klass) {
    var remove = 'hl-';

    return klass.split(/\s/).filter(function(k) {
        return k.indexOf(remove) === 0;
    }).join(' ');
});
Comments