views:

158

answers:

2

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);
+9  A: 

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
Paolo Bergantino
I guess he is looking for something like an ":only-text" selector. The children() method only helps if you have the id.
kgiannakakis
Yeah, I updated my answer to show how to do this.
Paolo Bergantino
Nice touch with the custom selector! No need to use the 'extend' method though - just do jQuery.expr[':].emptyOrText = function(){...}
J-P
Also, 0 converts to false and trying to access [0] is shorter than 'length' - ... So you can just do 'return !$(e).children()[0]'
J-P
Ah, I wasn't sure on the syntax for custom selectors, that is shorter. Thanks. As far as the length, I kind of like it with length as it reads better and someone coming across it later can make sense of it a little easier, I think.
Paolo Bergantino
nice answer, Paolo...this extends beyond the current question. I know I will return to this to solve future problems.
CarolinaJay65
+5  A: 

Get any element that doesn't have any other element:

$('*:not(:has(*))');
Borgar
It may be worth mentioning that this does not work the other way around: "*:has(:not(*))" fails for some internal reason.
Borgar