Reputation: 57
How to check if an element has a specific child?
I added children to my element using:
var child1 = document.createElement('div');
document.body.appendChild(child1);
How can I check whether child1
is already attached to body
?
if (document.body.alreadyHas(child1)) …
^^^^^^^^^^
what to do here?
Upvotes: 3
Views: 12159
Reputation: 13698
If you are sure element is direct child of a node, querySelector
and Node.contains
methods are wasteful because they will look into descendents also. Basically you will be searching the whole DOM tree, not only the direct children.
More performant alternative is, if you are going to look into elements only:
Array.from(parent.children).some(el => el === target);
If you want to check text nodes and everything:
Array.from(parent.childNodes).some(el => el === target);
The some
methods shortcuts and returns immediately when a matching child is found.
Upvotes: 0
Reputation: 152
you can find more about it here
const child1 = document.createElement('div');
document.body.appendChild(child1);
if(document.contains(child1)){
//your code
}
This answer that was posted earlier will throw an error in case the element doesn't exist, I wouldn't use it:
if(document.querySelector("div .example").length>0)
{
//your code
}
You can open your console in this page and test it:
VM113:1 Uncaught TypeError: Cannot read properties of null (reading 'length') at :1:39
If you want to use document.querySelector use this instead, it will return null if doesn't find any matches:
if(document.querySelector("div .example")){
// returns null if it div doesn't exist inside DOM
}
Upvotes: 2
Reputation: 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<html>
<div id="myDiv">
<p>tag p</p>
<strong>tag strong</strong>
<h5>title h5</h5>
</div>
<button type="button" onclick="myFunction()">Click here</button>
</html>
<script>
function myFunction(){
if(jQuery("#myDiv").children("h5").length > 0){
console.log("Found!");
}else{
console.log("Not Found!");
}
}
</script>
Upvotes: 0
Reputation: 150070
Given references to two elements, you can test if one is the child of the other by using the .parentElement
property as follows:
if (child1.parentElement === parent1) {
// do something
}
So in your specific case where you've said the parent is the body
, you can do this:
var child1 = document.createElement('div');
var child2 = document.createElement('div');
document.body.appendChild(child1); // note we only append one
if (child1.parentElement === document.body) {
console.log("child1 is a child of the body"); // this will run
}
if (child2.parentElement === document.body) {
console.log("child2 is a child of the body"); // this won't run
}
Upvotes: 6
Reputation: 1299
You can do that using HTML DOM querySelector()
Method .
if(document.querySelector("div .example").length>0)
{
//your code
}
Upvotes: 3