'How to check if an element has a specific child?
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?
Solution 1:[1]
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
}
Solution 2:[2]
You can do that using HTML DOM querySelector()
Method .
if(document.querySelector("div .example").length>0)
{
//your code
}
Solution 3:[3]
<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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nnnnnn |
Solution 2 | |
Solution 3 |