最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to use querySelector to select this element - Stack Overflow

programmeradmin0浏览0评论
<div class="parentDiv" >
   <button class="close" 
    data-dismiss="modal" 
    style="..." 
    aria-label="Close" 
    onclick='$(this).closest(".parentDiv").remove()'
    >
         <span class="glyphicon glyphicon-remove-circle small"></span>
    </button>

    <div class="alert alert-danger">{{ errorMsg }}</div>
</div>
...
...

In the above sample code, what strategy can I use to change the jQuery $(this) to pure javascript code like using querySelector?

Please note that I want to use Element.closest() because there will be many Div elements stacked on top of each other having "parentDiv" class name.

Basically, I want to select the parent and then remove that node after the cick on $(this) element.

So what's the best approach for doing this without using jQuery selector like $(this).closest('.parentDiv').remove() ?

And is it possible to do it without knowing the class name or ID of the current (this) element ?

<div class="parentDiv" >
   <button class="close" 
    data-dismiss="modal" 
    style="..." 
    aria-label="Close" 
    onclick='$(this).closest(".parentDiv").remove()'
    >
         <span class="glyphicon glyphicon-remove-circle small"></span>
    </button>

    <div class="alert alert-danger">{{ errorMsg }}</div>
</div>
...
...

In the above sample code, what strategy can I use to change the jQuery $(this) to pure javascript code like using querySelector?

Please note that I want to use Element.closest() because there will be many Div elements stacked on top of each other having "parentDiv" class name.

Basically, I want to select the parent and then remove that node after the cick on $(this) element.

So what's the best approach for doing this without using jQuery selector like $(this).closest('.parentDiv').remove() ?

And is it possible to do it without knowing the class name or ID of the current (this) element ?

Share Improve this question asked Jan 16, 2018 at 22:45 AndyAndy 2,6316 gold badges43 silver badges71 bronze badges 7
  • Which element are you trying to target? .parentDiv? Surely it would just be document.querySelector('.parentDiv') that you're looking for then? – Obsidian Age Commented Jan 16, 2018 at 22:47
  • Great! So if I do document.querySelector('.parentDiv') would it automatically give me the closest one ? Because there are several divs stacked on top of each other with parentDiv class name. (OK I am checking right now.) – Andy Commented Jan 16, 2018 at 22:49
  • No it does not. It is relative to document – bigless Commented Jan 16, 2018 at 22:49
  • Ahh, I see what you're trying to do now. Yep, you're looking for .parentNode. – Obsidian Age Commented Jan 16, 2018 at 22:50
  • Try this polyfill for closest developer.mozilla/en-US/docs/Web/API/Element/closest – Khauri Commented Jan 16, 2018 at 22:51
 |  Show 2 more ments

4 Answers 4

Reset to default 2

If a button is always nested in a parentDiv container just grab the parent node and remove it using parentNode and remove.

document.querySelector("button").addEventListener("click", function() {
   this.parentNode.remove();
});
<div>
<button>remove me</button>
</div>

Within an onclick :

<div>
<button onclick="this.parentNode.remove()">remove me</button>
</div>

You can also use parentNode property of your element. It will be without a usage of the class selector.

The code will be:

if (node.parentNode) {
  // remove a node from the tree, unless 
  // it's not in the tree already
  node.parentNode.removeChild(node);
}

This is why jQuery was created. Below is the equivalent JavaScript, which would handle multiple buttons, in which any of their ancestors (parent, grandparent, etc.) has the parentDiv class

// JS equivalent to $(this).closest('.parentDiv').remove()

var buttons = document.querySelectorAll('button.close');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', function() {
    var parent = this.parentNode;

    while (!parent.classList.contains('parentDiv')) {
      parent = parent.parentNode;
    }

    parent.parentNode.removeChild(parent);
  });
}

Snippet:

var buttons = document.querySelectorAll('button.close');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', function() {
    var parent = this.parentNode;

    while (!parent.classList.contains('parentDiv')) {
      parent = parent.parentNode;
    }

    parent.parentNode.removeChild(parent);
  });
}
.parentDiv {
  border: 1px solid black;
}
<div class="parentDiv">
  Parent 1
  <button class="close">
    Delete Parent 1
  </button>
</div>

<div class="parentDiv">
  Parent 2
  <span>
    <button class="close">
      Delete Parent 2
    </button>
  </span>
</div>

If for some reason you change your HTML and your button isn't the direct nested child of the node you want to remove, then potentially you you can just get rid of the jquery selector, with a minor caveat. Instead of $(this) just use this.

Element.closest has decent browser support (except for internet explorer), and if you're truly worried about browser support then there is also a polyfill.

Essentially one purpose of jquery is to enable standardized methods across browsers that might not support them yet, such as Element.closest. Unfortunately if you want full browser support, I don't think there's a one liner you can use to replace your statement using jquery. However, you can include only the parts you need, such as the Element.closest polyfill in a script tag (perhaps in the head of your html document).

<script>
// Optional Element.closest polyfill
if (!Element.prototype.matches)
    Element.prototype.matches = Element.prototype.msMatchesSelector || 
                                Element.prototype.webkitMatchesSelector;

if (!Element.prototype.closest){
    Element.prototype.closest = function(s) {
        var el = this;
        if (!document.documentElement.contains(el)) return null;
        do {
            if (el.matches(s)) return el;
            el = el.parentElement || el.parentNode;
        } while (el !== null && el.nodeType === 1); 
        return null;
    };
}

</script>

<div class="parentDiv" >
   <button class="close" 
    data-dismiss="modal" 
    style="..." 
    aria-label="Close" 
    onclick='this.closest(".parentDiv").remove()'
    >
         <span class="glyphicon glyphicon-remove-circle small">Remove</span>
    </button>

    <div class="alert alert-danger">{{ errorMsg }}</div>
</div>

发布评论

评论列表(0)

  1. 暂无评论