I want to apply a class 'solo' to a link in a paragraph where that link is the ONLY element in the paragraph.
So this would get the 'solo' class:
<p><a>I am alone</a></p>
But this would not:
<p><a>I am not alone</a> because there is more text!</p>
You could do:
$('p').filter(function() {
var $childNodes = $(this).contents();
return $childNodes
.not($childNodes.filter('a').first())
.not(function() {
return this.nodeType === 3 && $.trim(this.nodeValue) === '';
}).length === 0;
});
This gets all child nodes (including text nodes) and removes the first a element it finds and all text nodes only containing whitespaces from that set. If the resulting set is empty, the link was the only child (alone).
Reference: filter, not, contents, Node.nodeType, trim
Update: Maybe this could be done easier, but I wanted it to work also for the case your HTML contains line breaks, which would result in text nodes containing only whitespaces:
<p>
<a>I am alone</a>
</p>
<p>
<a>I am not alone</a> because there is more text!
</p>
DEMO
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