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)?
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.
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).
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 .
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.
You can use a non recursive helper function, for example:
function nthParent(element, n) {
while(n-- && element)
element = element.parentNode;
return element;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With