Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jquery, how can I detect if a paragraph contains one link and only one link, nothing else

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>
like image 289
phirschybar Avatar asked Jan 23 '26 06:01

phirschybar


1 Answers

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

like image 87
Felix Kling Avatar answered Jan 25 '26 20:01

Felix Kling