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?
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.
CSS selector is selecting all p elements in page.
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.
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.
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");
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/
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