What would the most efficient method be to find a child element of (with class or ID) of a particular parent element using pure javascript only. No jQuery or other frameworks.
In this case, I would need to find child1 or child2 of parent, assuming that the DOM tree could have multiple child1 or child2 class elements in the tree. I only want the elements of parent
<div class="parent">
<div class="child1">
<div class="child2">
</div>
</div>
</div>
This question is related to
javascript
dom
Just adding another idea you could use a child selector to get immediate children
document.querySelectorAll(".parent > .child1");
should return all the immediate children with class .child1
You have a parent element, you want to get all child of specific attribute
1. get the parent
2. get the parent nodename by using parent.nodeName.toLowerCase()
convert the nodename to lower case e.g DIV will be div
3. for further specific purpose, get an attribute of the parent e.g parent.getAttribute("id")
. this will give you id
of the parent
4. Then use document.QuerySelectorAll(paret.nodeName.toLowerCase()+"#"_parent.getAttribute("id")+" input " );
if you want input children of the parent node
let parent = document.querySelector("div.classnameofthediv")_x000D_
let parent_node = parent.nodeName.toLowerCase()_x000D_
let parent_clas_arr = parent.getAttribute("class").split(" ");_x000D_
let parent_clas_str = '';_x000D_
parent_clas_arr.forEach(e=>{_x000D_
parent_clas_str +=e+'.';_x000D_
})_x000D_
let parent_class_name = parent_clas_str.substr(0, parent_clas_str.length-1) //remove the last dot_x000D_
let allchild = document.querySelectorAll(parent_node+"."+parent_class_name+" input")
_x000D_
If you already have var parent = document.querySelector('.parent');
you can do this to scope the search to parent
's children:
parent.querySelector('.child')
Source: Stackoverflow.com