Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize the code like "this.parentNode.parentNode.parentNode..."?

Tags:

javascript

var topClick = function() {
  child = this.parentNode.parentNode.parentNode.parentNode;
  child.parentNode.removeChild(child);
  var theFirstChild = document.querySelector(".m-ctt .slt");
  data[child.getAttribute("data-id")].rank = 5;
  insertBlogs();
};

As you see, there is a part of my code like this:

this.parentNode.parentNode.parentNode.parentNode;  

Is there another way to optimize the code (without using jQuery)?

like image 509
yaochiqkl Avatar asked Feb 01 '16 11:02

yaochiqkl


People also ask

What is parentNode parentNode in Javascript?

The read-only parentNode property of the Node interface returns the parent of the specified node in the DOM tree. Document and DocumentFragment nodes can never have a parent, so parentNode will always return null . It also returns null if the node has just been created and is not yet attached to the tree.

What is parentNode in jQuery?

parentNode is native JS, where parent() is not. What you are doing in your code is wrapping the DOM elements in the jQuery object so you can call jQuery specific methods on it. So, you cannot call index() on just this. parentNode, but you can call it on $(this. parentNode).

Why is parentNode null?

Introduction to parentNode attribute The parentNode is read-only. The Document and DocumentFragment nodes do not have a parent. Therefore, the parentNode will always be null . If you create a new node but haven't attached it to the DOM tree, the parentNode of that node will also be null .

How do I select parent nodes?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it. In HTML, the document is itself the parent node of html element.


2 Answers

You can use a non recursive helper function, for example:

function nthParent(element, n) {
  while(n-- && element)  
    element = element.parentNode;
  return element;
}
like image 117
hansmaad Avatar answered Oct 11 '22 16:10

hansmaad


You can use recursive helper function, for example:

function getNthParent(elem, n) {
    return n === 0 ? elem : getNthParent(elem.parentNode, n - 1);
}

var child = getNthParent(someElement, 4);
like image 31
madox2 Avatar answered Oct 11 '22 15:10

madox2