Ben
Ben

Reputation: 257

prevent event on target and it's parent

I have this code which i use to remove a classname "joker" from every element that has this classname: http://jsfiddle.net/ffz30knn/1/

Is it possible (with vanilla JS only) to prevent this event on the target element and it's parent, so when i click <span class="joker">one</span> which is inside <div class="joker"></div> it will remove the "joker" class from other elements that has this class but not from this span element and it's wrapping div?

Thanks.

Here is the current code:

function removeClass(classToRemove) {
  var elems = document.getElementsByClassName(classToRemove);
  console.log(elems.length);
  if (!elems) return;
  for (var i = elems.length - 1; i >= 0; i--) {
    var elem = elems[i];
    elem.className = elem.className.replace(/(?:^|\s)joker(?!\S)/g, '');
  }
}
window.onload = function() {
  document.onclick = function() {
    removeClass("joker");
  };
};
div {
  background: silver;
  padding: 3px 8px;
  margin: 5px;
}
span {
  background: blue;
  padding: 3px 8px;
  color: white;
}
.joker {
  background: black;
  color: red;
}
<div class="one two three joker"><span class="joker">one</span>
</div>
<div class="one two three"><span>two</span>
</div>
<div class="one two three joker"><span class="joker">three</span>
</div>
<div class="one two three"><span>four</span>
</div>

Upvotes: 1

Views: 243

Answers (2)

The F
The F

Reputation: 3714

You can get the element you've clicked through the onclick event:

window.onload=function() {
    document.onclick=function(event) {
        removeClass(event.target, "joker");
    };
};

Pass that to your function and you should be able to achieve what you desire.

function removeClass(skip, classToRemove){
    var elems = document.getElementsByClassName(classToRemove);
    if (!elems) return;
    for (var i=elems.length-1;i>=0;i--) {
        var elem = elems[i];
        if (elem == skip || elem == skip.parentElement) {
           return
        } else {
            elem.className = elem.className.replace( /(?:^|\s)joker(?!\S)/g,'' ); 
        }
    }
}

Here an updated fiddle

Upvotes: 1

Jo Colina
Jo Colina

Reputation: 1924

If I understand you want to delete the class joker from every element BUT the one you clicked?

In your removeClass function you can check if it is the same element

function removeClass(classToRemove) {
  var elems = document.getElementsByClassName(classToRemove);
  console.log(elems.length);
  if (!elems) return;
  for (var i = elems.length - 1; i >= 0; i--) {
    var elem = elems[i];
    if(elem != this)
        elem.className = elem.className.replace(/(?:^|\s)joker(?!\S)/g, '');
   }
}

And I guess you can check for the parent element by doing Element.parentElement, so that would give you:

if(elem != this && elem != this.parentElement)

Upvotes: 1

Related Questions