How can I target this element using the querySelector method?

<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>
...
...

If I want to change the jQuery $(this) to pure JavaScript using querySelector, particularly for selecting the parent element with the "parentDiv" class name and removing it upon clicking on the element:

Note that Element.closest() should be used because there are multiple stacked Div elements with the "parentDiv" class name.

The goal is to target the parent element effectively without relying on the jQuery selector $(this).closest('.parentDiv').remove(). Is it feasible to achieve this without having prior knowledge of the current element's class or ID?

Answer â„–1

To easily remove a button that is always nested in a parentDiv container, you can grab the parent node and use parentNode along with remove method.

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

Alternatively, within an onclick event:

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

Answer â„–2

Another way to manipulate the DOM is by utilizing the parentNode property of the element. This method does not require the use of a class selector.

Here is an example of how to implement this:

if (element.parentNode) {
  // Remove the element from the DOM
  // Only if it is currently in the tree
  node.parentNode.removeChild(node);
}

Answer â„–3

One of the main reasons for the creation of jQuery was to simplify tasks like handling multiple buttons within elements that have a specific ancestor with a certain class, such as the parentDiv class.

// JavaScript 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>

Answer â„–4

In the event that you make changes to your HTML and find that your button is no longer a direct child of the node you wish to remove, there is an alternative solution. You can eliminate the jQuery selector by simply using this instead of $(this).

Element.closest is well-supported in browsers (excluding Internet Explorer), but if you have concerns about browser compatibility, a polyfill is available.

jQuery's main purpose is to provide standardized methods across browsers that may not yet support them, like Element.closest. To achieve full browser support, it seems that there isn't a simple one-liner replacement for using jQuery. However, you can selectively include necessary components, such as the Element.closest polyfill within a script tag in the head section 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

PHP Script receives a pair of results from GetJSON for a single posted value

As I attempt to utilize .getJSON to send one value to a specific URL and receive all corresponding values for that input, I encounter the following scenario: All the values are securely stored in a MySQL MyISAM table. The request function is presented as ...

Step-by-step guide on achieving 100% height for a child element within a parent using Flexbox

Currently facing an issue where trying to make a child element take up 100% of the remaining height of its parent container causes the child's height to go beyond the boundaries of the parent. HTML .container { height: 340px; /* background-i ...

Troubleshooting the "Request failed with status code 500" error when refreshing a page in a React application

Every time the page is reloaded, an error message pops up saying: Uncaught (in promise) Error: Request failed with status code 500. Here's the code in list.tsx: const [state, setState] = useState([]); const { getRoom } = useRoom(); const fe ...

Having issues with JQuery.Ajax() function, not entirely certain if the script is loading correctly

Attempting to utilize an API for sending emails through MailChimp without needing a backend. Unsure if Jquery script file is configured properly. $(document.ready(function () { $('#survey').click(function() { $.ajax({ type: “POSTâ ...

Update the package.json file by adding a new command to an existing script

Is it possible to automatically run npm install before starting the application with npm start? Here is what my package.json file currently looks like: . . "scripts": { "test": "echo \"Error: no test specified\ ...

Hover over to reveal sliding menu

Hey everyone! Take a look at this code snippet: <body> <div id="slidemenubar"> <a href="">1</a> </div><br> <div id="slidemenubar2"> <a href="">2</a> </div> </body> When hovering over the ...

Is there a way to prevent the repositioning of bootstraps (reactstrap) drop-down menu when the screen sizes are altered?

When in portrait mode, there is ample space for the drop-down menu to display below the button you click to reveal it: https://i.sstatic.net/WEgYl.png However, when the screen size shrinks (such as in landscape mode on certain mobile devices), the menu&a ...

Unable to connect to server using local IP address

Currently utilizing a freezer application () and encountering an issue where I can only access the server on localhost. I attempted to modify the settings.js file by replacing 127.0.0.1 with 0.0.0.0, rebuilt it, but it still persists on localhost. Even aft ...

In Angular 5, you can easily prevent interaction with a related button by disabling it when the corresponding reactive

I recently encountered a situation where I needed to implement a reactive form in a component. It looked something like this... form component.html <form [formGroup]="form" class="do-form"> <div formGroupName="dot"> <div class ...

Can Highchart dynamically adjust color choices based on the quantity of data points available?

I am trying to figure out how to import a specific color palette into my column graph. I want to use different color palettes based on the number of data points in my graph - for 3 or fewer points, I want to use the top row colors, for 4 points I want to u ...

Tips for adjusting the appearance of text dynamically using JavaScript and CSS when a button is clicked

I'm trying to change the color of the text after a button click. Currently, the text color is blue before clicking the button, but I want it to be green after the click. I've searched online for solutions, but I haven't been successful. Here ...

Why are the $refs always empty or undefined within Vue components?

I am completely new to working with Vue and I've been attempting to utilize $refs to retrieve some elements within the DOM from a sibling component. My objective is very basic, as I just need to obtain their heights, but I haven't had much succes ...

Is there a way to include text in a video similar to the style used by PayPal?

PayPal uses the tagline "You Make it, We'll Pay It" displayed on top of a video with a subtle play button located in the corner. By clicking this play button, the video initiates playback and smoothly transitions from a dark overlay to the video itsel ...

Basic animation created using Three.js

I'm currently experimenting with a basic color animation in Three.js. Below is the code I am using: const geometry = new THREE.BoxGeometry(1, 1, 1); const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); const cube = new THREE.Mesh(geomet ...

Encountering error TS2307: Module 'redux' not found when trying to implement redux in Angular 7

Currently, I am diving into the world of Redux and attempting to integrate it into my Angular 7 project using ng2-redux. However, upon visiting the npm page, I discovered that the recommended approach was to install it with npm install @angular-redux/store ...

What is preventing d3.json from including cookies in the request?

I'm delving into the world of ajax requests with d3.js (v5) and I'm facing a little hiccup. Here's my code snippet: d3.json(uri).then(data =>console.log(data)); When I tried this in an app utilizing cookie authentication, I consistently ...

Aligning two separate divs within a parent container div

I'm seeking a solution to the following issue: I have a container div that adjusts its height and width based on a div/img inside it with dynamic height. Inside that container, I want to add another square div measuring 72x72px that will be centered ...

The styles defined in CSS do not have an impact on EJS templates that have GET route paths stacked

I have a CSS file located in the public directory and two EJS templates in the views directory. The CSS file works fine when using this route: app.get('/theresa', (req, res) => { res.render('templates/home') }) However, when I ...

Ways to display the main image on a blog post

This piece of code is designed for displaying the relevant post associated with wp_ai1ec_events function display_event($atts ) { global $wpdb; $event = $wpdb->get_results("SELECT * FROM wp_ai1ec_events ORDER BY start"); ...

Vue.js error: Reaching maximum call stack size due to failed data passing from parent to child component

I'm having trouble passing data from a parent component to a child component. I tried using props and returning data, but with no success. The parent component is a panel component that contains the data, while the child component is a panelBody. Thi ...