简体   繁体   中英

Removing attributes of an element on clicking outside with Vanilla JS

How can I remove an attribute of an element on click outside or on another div of same type? Here's my code:

HTML:

<div id="container">
  <div data-something></div>
  <div data-something></div>
</div>

JavaScript:

var elements = document.querySelectorAll("[data-something]");    

Array.prototype.forEach.call(elements, function(element) {

  // Adding
  element.onclick = function() {
    this.setAttribute("data-adding", "");
  };

  // Removing -- Example
  element.onclickoutside = function() {
     this.removeAttribute("data-adding");
  };

});

I would probably use a click handler on the document , and then remove the attribute from any element that had it that wasn't in the bubbling path.

document.addEventListener("click", function(e) {
    Array.prototype.forEach.call(document.querySelectorAll("*[data-adding][data-something]"), function(element) {
        var node, found = false;
        for (node = e.target; !found && node; node = node.parentNode) {
            if (node === element) {
                found = true;
            }
        }
        if (!found) {
            element.removeAttribute("data-adding");
        }
    });
}, false);

...or something along those lines.

Live Example:

  document.addEventListener("click", function(e) { Array.prototype.forEach.call(document.querySelectorAll("*[data-adding]"), function(element) { var node, found = false; for (node = e.target; !found && node; node = node.parentNode) { if (node === element) { found = true; } } if (!found) { element.removeAttribute("data-adding"); } }); }, false); 
 *[data-adding] { color: red; } 
 <div data-adding data-something>One</div> <div data-adding data-something>Two</div> 

You can use Node.contains() inside a global click event handler to check if a click is outside an element, and handle the event appropriately:

 box = document.getElementById('box'); lastEvent = document.getElementById('event'); box.addEventListener('click', function(event) { // click inside box // (do stuff here...) lastEvent.textContent = 'Inside'; }); window.addEventListener('click', function(event) { if (!box.contains(event.target)) { // click outside box // (do stuff here...) lastEvent.textContent = 'Outside'; } }); 
 #box { width: 200px; height: 50px; background-color: #ffaaaa; } 
 <div id="box">Click inside or outside me</div> <div>Last event: <span id="event">(none)</span> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM