How to define n-th parent element by pure JavaScript? - javascript

As in the title,
how can i define nth parentElement in js in other way than:
var theComment = e.target.parentElement.parentElement.parentElement.parentElement;

You can write a loop for it:
const n = 4
let elem = e.target
for(let i = 0; i < n; i++)
elem = elem.parentElement
console.log(elem)
However, as mentioned in the comments, if you're looking for a specific element, it might be better to just write a selector for the element you're looking for.
This applies to your case even more, as event.target can return child nodes of the watched element (if the event bubbles), making your parent count shift around a bit.

You might define a function which ascends up in the parent hierarchy with a loop, e.g.:
function nthParent(n, el) {
while (n--) {
el = el.parentElement;
if (!el) return null;
}
return el;
}

Related

Add class for all parents element on native JavaScript

If I have some ".blocks"
body
section
.main-container
.container
.block
.blcok
And I need add className for all parents block, div, section, body.
When I use jquwry I wrote like this:
$(".block").parents().addClass('block-wrapp');
But now I must use native js.
window.onload = function() {
let block = document.getElementsByClassName('block');
for( let i = 0; i < block.length; i++ ) {
block[i].parentNode.classList.add('block-wrapp');
}
};
I try use
let mainBlock = block[i].parentNode.className;
console.log(mainBlock.parentNode);
But it doesn't work
Try changing your parentNode to parentElement inside the loop
Loop through all parents with a while statement:
// loop through selected elements
for( let i = 0; i < block.length; i++ ) {
// get current looped element
let node = block[i];
// do this as long as we have a parent to go to
while (let parent = node.parentNode) {
// add class on parent
parent.classList.add('block-wrapp');
// move up the tree
node = parent;
}
}
You can improve a bit the performance so you don't visit the same parents and traverse the entire tree over and over again for sibling elements. For this, get a list of processed parents and skip them the next time you encounter them:
let visitedParents = [];
while (parent = node.parentNode && visitedParents.indexOf(parent) === -1) {
// ...
// mark this parent as visited
visitedParents.push(parent);
}
Finally, you should also stop when reaching the body element, otherwise you'll reach html and the document, which I presume you don't want to:
while (node.parentNode !== document.body && .... ) { ... }

How to write Javascript to search nodes - without getElementsByClassName

I'm very new at recursion, and have been tasked with writing getElementsByClassName in JavaScript without libraries or the DOM API.
There are two matching classes, one of which is in the body tag itself, the other is in a p tag.
The code I wrote isn't working, and there must be a better way to do this. Your insight would be greatly appreciated.
var elemByClass = function(className) {
var result = [];
var nodes = document.body; //<body> is a node w/className, it needs to check itself.
var childNodes = document.body.childNodes; //then there's a <p> w/className
var goFetchClass = function(nodes) {
for (var i = 0; i <= nodes; i++) { // check the parent
if (nodes.classList == className) {
result.push(i);
console.log(result);
}
for (var j = 0; j <= childNodes; j++) { // check the children
if (childNodes.classList == className) {
result.push(j);
console.log(result);
}
goFetchClass(nodes); // recursion for childNodes
}
goFetchClass(nodes); // recursion for nodes (body)
}
return result;
};
};
There are some errors, mostly logical, in your code, here's what it should have looked like
var elemByClass = function(className) {
var result = [];
var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
(function goFetchClass(nodes) {
for (var i = 0; i < nodes.length; i++) {
if ( pattern.test(nodes[i].className) ) {
result.push(nodes[i]);
}
goFetchClass(nodes[i].children);
}
})([document.body]);
return result;
};
Note the use of a regex instead of classList, as it makes no sense to use classList which is IE10+ to polyfill getElementsByClassName
Firstly, you'd start with the body, and check it's className property.
Then you'd get the children, not the childNodes as the latter includes text-nodes and comments, which can't have classes.
To recursively call the function, you'd pass the children in, and do the same with them, check for a class, get the children of the children, and call the function again, until there are no more children.
Here are some reasons:
goFetchClass needs an initial call after you've defined it - for example, you need a return goFetchClass(nodes) statement at the end of elemByClass function
the line for (var i = 0; i <= nodes; i++) { will not enter the for loop - did you mean i <= nodes.length ?
nodes.classList will return an array of classNames, so a direct equality such as nodes.classList == className will not work. A contains method is better.
Lastly, you may want to reconsider having 2 for loops for the parent and children. Why not have 1 for loop and then call goFetchClass on the children? such as, goFetchClass(nodes[i])?
Hope this helps.

Need help finding/traversing dom in Javascript

I'm sure this is a redundant question, but I've looked for an hour or so and come up empty-handed so was hoping someone could help...
Looking for a way to use JS (not jquery) to return the class of the li below when searching for 'Chicken' (or whatever the value is).
<li class='113252'>
<span>Chicken</span>
</li>
So was hoping the javascript would return the li class when given the span value (in this case Chicken).
Thanks!
Try this:
var spanArray = document.getElementsByTagName('span');
for (var i=0; i<spanArray.length; i++) {
if(spanArray[i].innerHTML.toUpperCase() === 'CHICKEN')
{
alert(spanArray[i].parentNode.className);
break;
}
}
Now, I'm more familiar with jQuery but seems to work in the fiddle linked here: http://jsfiddle.net/FranWahl/fCzYc/2/ (Updated to include suggested break; after match)
You can add more type checking for the parentNode to ensure it is an li and so on, but this should get you started.
Also, I'm not sure at all how efficient this is in a big document.
Edit
Having read through some comments I have updated my code above to include the break as suggested by ajax333221.
Dennis mentioned that it would be better to call getElementByTagName on the ul.
Given you can have an li without a ul I added it here as separate code as I'm not sure if the OP has ul tags.
Code querying against each ul (jsFiddle here)
var ulArray = document.getElementsByTagName('ul');
var parentFound = false;
for (var i = 0; i < ulArray.length; i++) {
var spanArray = ulArray[i].getElementsByTagName('span');
for (var i = 0; i < spanArray.length; i++) {
if (spanArray[i].innerHTML.toUpperCase() === 'CHICKEN') {
alert(spanArray[i].parentNode.className);
parentFound = true;
break;
}
}
if(parentFound)
{
break;
}
}​
This is by no means fully complete, which is why you should seek a library, but it does two things:
recursively traverse child elements (starting with the document's BODY), to find the supplied text
recursively traverse the parent element to find the supplied parent element tag, once found it will return the class of that parent
JSFiddle: http://jsfiddle.net/vol7ron/bttQN/
function getParentClass(element, parentTag){
if (element.tagName == parentTag.toUpperCase())
return element.className;
return getParentClass(element.parentNode,parentTag);
}
window.findParentClass = function (text,tagName){
var elements = document.getElementsByTagName('body');
for (var n=elements.length; n--;){
var foundClass = (function searchNextChild(el){
if (!el.children.length) {
if (el.textContent == text)
return getParentClass(el,tagName);
return;
}
for (var i=0, n=el.children.length; i<n; i++)
return searchNextChild(el.children[i]);
})(elements[n]);
return foundClass;
}
};
Example Call:
alert( findParentClass('Chicken','li') );

how to get all parent nodes of given element in pure javascript?

I mean an array of them. That is a chain from top HTML to destination element including the element itself.
for example for element <A> it would be:
[HTML, BODY, DIV, DIV, P, SPAN, A]
A little shorter (and safer, since target may not be found):
var a = document.getElementById("target");
var els = [];
while (a) {
els.unshift(a);
a = a.parentNode;
}
You can try something like:
var nodes = [];
var element = document.getElementById('yourelement');
nodes.push(element);
while(element.parentNode) {
nodes.unshift(element.parentNode);
element = element.parentNode;
}
I like this method:
[...(function*(e){do { yield e; } while (e = e.parentNode);})($0)]
... where $0 is your element.
An upside of this method is that it can be used as a value in expressions.
To get an array without the target element:
[...(function*(e){while (e = e.parentNode) { yield e; }})($0)]
You can walk the chain of element.parentNodes until you reach an falsey value, appending to an array as you go:
const getParents = el => {
for (var parents = []; el; el = el.parentNode) {
parents.push(el);
}
return parents;
};
const el = document.querySelector("b");
console.log(getParents(el).reverse().map(e => e.nodeName));
<div><p><span><b>Foo</b></span></div>
Note that reversing is done in the caller because it's not essential to the lineage algorithm. Mapping to e.nodeName is purely for presentation and also non-essential.
Note that this approach means you'll wind up with the document element as the last element in the chain. If you don't want that, you can add && el !== document to the loop stopping condition.
The overall time complexity of the code above is linear and reverse() is in-place, so it doesn't require an extra allocation. unshift in a loop, as some of the other answers recommend, is quadratic and may harm scalability on uncommonly-deep DOM trees in exchange for a negligible gain in elegance.
Another alternative (based on this):
for(var e = document.getElementById("target"),p = [];e && e !== document;e = e.parentNode)
p.push(e);
I believe this will likely be the most performant in the long run in the most scenarios if you are making frequent usage of this function. The reason for why t will be more performant is because it initially checks to see what kind of depths of ancestry it might encounter. Also, instead of creating a new array every time you call it, this function will instead efficiently reuse the same array, and slice it which is very optimized in some browsers. However, since there is no really efficient way I know of to check the maximum depth, I am left with a less efficient query-selector check.
// !IMPORTANT! When moving this coding snippet over to your production code,
// do not run the following depthtest more than once, it is not very performant
var kCurSelector="*|*", curDepth=3;
while (document.body.querySelector(kCurSelector += '>*|*')) curDepth++;
curDepth = Math.pow(2, Math.ceil(Math.log2(startDepth))),
var parentsTMP = new Array(curDepth);
function getAllParentNodes(Ele){
var curPos = curDepth;
if (Ele instanceof Node)
while (Ele !== document){
if (curPos === 0){
curPos += curDepth;
parentsTMP.length <<= 1;
parentsTMP.copyWithin(curDepth, 0, curDepth);
curDepth <<= 1;
}
parentsTMP[--curPos] = Ele;
Ele = Ele.parentNode;
}
return retArray.slice(curPos)
}
The browser compatibility for the above function is that it will work in Edge, but not in IE. If you want IE support, then you will need a Array.prototype.copyWithin polyfill.
get all parent nodes of child in javascript array
let selectedTxtElement = document.getElementById("target");
let els = [];
while (selectedTxtElement) {
els.unshift(selectedTxtElement);
selectedTxtElement = selectedTxtElement.parentNode;
}
know more

How do I make this loop all children recursively?

I have the following:
for (var i = 0; i < children.length; i++){
if(hasClass(children[i], "lbExclude")){
children[i].parentNode.removeChild(children[i]);
}
};
I would like it to loop through all children's children, etc (not just the top level). I found this line, which seems to do that:
for(var m = n.firstChild; m != null; m = m.nextSibling) {
But I'm unclear on how I refer to the current child if I make that switch? I would no longer have i to clarify the index position of the child. Any suggestions?
Thanks!
Update:
I'm now using the following, according to answer suggestions. Is this the correct / most efficient way of doing so?
function removeTest(child) {
if (hasClass(child, "lbExclude")) {
child.parentNode.removeChild(child);
}
}
function allDescendants(node) {
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
allDescendants(child);
removeTest(child);
}
}
var children = temp.childNodes;
for (var i = 0; i < children.length; i++) {
allDescendants(children[i]);
};
function allDescendants (node) {
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
allDescendants(child);
doSomethingToNode(child);
}
}
You loop over all the children, and for each element, you call the same function and have it loop over the children of that element.
Normally you'd have a function that could be called recursively on all nodes. It really depends on what you want to do to the children. If you simply want to gather all descendants, then element.getElementsByTagName may be a better option.
var all = node.getElementsByTagName('*');
for (var i = -1, l = all.length; ++i < l;) {
removeTest(all[i]);
}
There's no need for calling the 'allDescendants' method on all children, because the method itself already does that. So remove the last codeblock and I think that is a proper solution (á, not thé =])
function removeTest(child){
if(hasClass(child, "lbExclude")){
child.parentNode.removeChild(child);
}
}
function allDescendants (node) {
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
allDescendants(child);
removeTest(child);
}
}
var children = allDescendants(temp);
You can use BFS to find all the elements.
function(element) {
// [].slice.call() - HTMLCollection to Array
var children = [].slice.call(element.children), found = 0;
while (children.length > found) {
children = children.concat([].slice.call(children[found].children));
found++;
}
return children;
};
This function returns all the children's children of the element.
The most clear-cut way to do it in modern browsers or with babel is this. Say you have an HTML node $node whose children you want to recurse over.
Array.prototype.forEach.call($node.querySelectorAll("*"), function(node) {
doSomethingWith(node);
});
The querySelectorAll('*') on any DOM node would give you all the child nodes of the element in a NodeList. NodeList is an array-like object, so you can use the Array.prototype.forEach.call to iterate over this list, processing each child one-by-one within the callback.
If you have jquery and you want to get all descendant elements you can use:
var all_children= $(parent_element).find('*');
Just be aware that all_children is an HTML collection and not an array. They behave similarly when you're just looping, but collection doesn't have a lot of the useful Array.prototype methods you might otherwise enjoy.
if items are being created in a loop you should leave a index via id="" data-name or some thing. You can then index them directly which will be faster for most functions such as (!-F). Works pretty well for 1024 bits x 100 items depending on what your doing.
if ( document.getElementById( cid ) ) {
return;
} else {
what you actually want
}
this will be faster in most cases once the items have already been loaded. only scrub the page on reload or secure domain transfers / logins / cors any else and your doing some thing twice.
If you use a js library it's as simple as this:
$('.lbExclude').remove();
Otherwise if you want to acquire all elements under a node you can collect them all natively:
var nodes = node.getElementsByTagName('*');
for (var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if (hasClass(n, 'lbExclude')) {
node.parentNode.removeChild(node);
}
}
To get all descendants as an array, use this:
function getAllDescendants(node) {
var all = [];
getDescendants(node);
function getDescendants(node) {
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
getDescendants(child);
all.push(child);
}
}
return all;
}
TreeNode node = tv.SelectedNode;
while (node.Parent != null)
{
node = node.Parent;
}
CallRecursive(node);
private void CallRecursive(TreeNode treeNode)
{
foreach (TreeNode tn in treeNode.Nodes)
{
//Write whatever code here this function recursively loops through all nodes
CallRecursive(tn);
}
}

Categories

Resources