Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting <p> elements that have not text nodes in jQuery

I have this HTML structure:

<div class="article-body">
<p>
    <a href="http://www.example.com">My Link</a>
Lorem Ipsum Dolor Sit amet.

</p>
<p><a href="http://www.example.com">Link that I must select.</a></p>
</div>​

and I must apply a class to the second link, the one without text nodes. I tried "p:empty a" and "p > a:only-child" but they don't work... There is a way to select it using jQuery?

like image 506
Giuppe Avatar asked Oct 30 '12 20:10

Giuppe


People also ask

How to select a particular element in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Which selects all the p elements on the page?

CSS selector is selecting all p elements in page.

How to select node in jQuery?

The textNodes of any element can be selected using jQuery by selecting all the nodes and using the filter() method to check the nodeType property. The required element is first selected using the jQuery selector. The contents() method is used on selected elements.

What is a text node?

A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.


2 Answers

Can't do with selector, but you can use filter() to perform custom selection:

$('p').filter(function(){
    var $clone = $(this).clone();
    $clone.children().remove();
    return !$clone.text();
}).addClass("red");​

Here, have a fiddle: http://jsfiddle.net/adrianonantua/5daYT/

:)

Update

As per @dfsq suggestion, we can take advantage of end() and make this same logic in one line:

$('p').filter(function(){
    return !$(this).clone().children().remove().end().text();
}).addClass("red");​
like image 176
Adriano Carneiro Avatar answered Nov 15 '22 07:11

Adriano Carneiro


Another solution with filter():

$("p").filter(function() {
    return $(this).contents().filter(function() {
        return this.nodeType == 3 && $.trim(this.nodeValue) != "";
    }).length == 0;
}).addClass("myClass")​;

DEMO: http://jsfiddle.net/wyvLC/

like image 29
VisioN Avatar answered Nov 15 '22 08:11

VisioN