the empty selector says that: Matches all elements that have no children (including text nodes).
Finds all elements that are empty - they don't have child elements or text.
What i want is to get elements which has no children but may have text inside., how?
UPDATE:
Example:
I want select these elements which has no children but may have text, with syntax like this:
$('div:empty, a:empty, span, p:empty, td:empty, img, input').mousemove(myMouseOverHandler);
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 . Whitespace and comments inside a node are also considered as text and comment nodes.
Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.
Get any element that doesn't have any other element:
$('*:not(:has(*))');
If an element has only text, children()
will have a length of 0
:
<div id="test1">
Hello World
</div>
<div id="test2">
<b>Hey there</b>
</div>
<script>
alert($("#test1").children().length); // alerts 0
alert($("#test2").children().length); // alerts 1 (the bold tag)
</script>
EDIT: In response to your edit, jQuery is awesome enough to let you do custom filters:
$.expr[':'].emptyOrText = function(e) {
return $(e).children().length == 0;
};
So, using the above against the HTML above, you could do this:
$('div:emptyOrText'); // will select #test1
I made a pure JavaScript function for anyone that does not want to use jQuery.
const getElementsWithNoChildren = (target) => {
let candidates;
if (target && typeof target.querySelectorAll === 'function') {
candidates = target.querySelectorAll('*');
}
else if (target && typeof target.length === 'number') {
candidates = target;
}
else {
candidates = document.querySelectorAll('*');
}
return Array.from(candidates).filter((elem) => {
return elem.children.length === 0;
});
};
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