Getting the Parent Div of Element

Getting the parent div of element

You're looking for parentNode, which Element inherits from Node:

parentDiv = pDoc.parentNode;

Handy References:

  • DOM2 Core specification - well-supported by all major browsers
  • DOM2 HTML specification - bindings between the DOM and HTML
  • DOM3 Core specification - some updates, not all supported by all major browsers
  • HTML5 specification - which now has the DOM/HTML bindings in it

Get parent div id by clicking on a child element

Use $(this) instead of $('.btn') since you want to target the specific element

var getParentID = $(this).parent().attr('id');
Once the id is available use jquery id selector to target the element

$(document).ready(function() {  $('.btn').on('click', function() {    var getParentID = $(this).parent().attr('id');    $("#" + getParentID).remove();  });});
#box {  width: 200px;  height: 200px;  background: black;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class='some classes' id='box1'>  <span class='btn btn-primary'>Close this div</span></div><div class='some classes' id='box2'>  <span class='btn btn-primary'>Close this div</span></div>

How to climb to specific parent element by JavaScript?

You can't move from child element to parent element using document.querySelector(). However, there are multiple ways to select the parent of an element.

You can use Element.closest() method to get the closest ancestor element with the specified CSS selector.

document.querySelector(".text").closest('.comments');

.closest() method will traverse the .text element and its ancestor elements (heading towards the document root) until it finds a node that matches the provided CSS selector.

If the element on which .closest() method is called, matches the provided CSS selector, then that element is returned otherwise .closest() method returns the matching ancestor or null if not match is found.

Jquery: How to get parent div of an element and clone it?

Notice that you have used arrow function because of which this is referring to the window.

There are two solutions for it :

1. Using event.target in the arrow function to get the targeted element.



Leave a reply



Submit