To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false .
To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
jQuery children() Method The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.
if ( $('#myfav').children().length > 0 ) {
// do something
}
This should work. The children()
function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.
This snippet will determine if the element has children using the :parent
selector:
if ($('#myfav').is(':parent')) {
// do something
}
Note that :parent
also considers an element with one or more text nodes to be a parent.
Thus the div
elements in <div>some text</div>
and <div><span>some text</span></div>
will each be considered a parent but <div></div>
is not a parent.
Another option, just for the heck of it would be:
if ( $('#myFav > *').length > 0 ) {
// do something
}
May actually be the fastest since it strictly uses the Sizzle engine and not necessarily any jQuery, as it were. Could be wrong though. Nevertheless, it works.
There's actually quite a simple native method for this:
if( $('#myfav')[0].hasChildNodes() ) { ... }
Note that this also includes simple text nodes, so it will be true for a <div>text</div>
.
and if you want to check div has a perticular children(say <p>
use:
if ($('#myfav').children('p').length > 0) {
// do something
}
You can also check whether div has specific children or not,
if($('#myDiv').has('select').length>0)
{
// Do something here.
console.log("you can log here");
}
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