Stas Bichenko
Stas Bichenko

Reputation: 13263

jQuery: select first anchor that contains any text

Consider the following markup:

<a href="#"></a>
<a href="#"><img src="foo.png" /></a>
<a href="#">aaa</a>
<a href="#">bbb</a>

Is it possible to use a jQuery selector to get the first anchor that contains any text (but not if it contains only image(s))? (In this case, the aaa one)

Upvotes: 0

Views: 2291

Answers (5)

Luca Fagioli
Luca Fagioli

Reputation: 13349

This will return the first anchor with text from a container, without looping through all the elements.

var getFirstAnchorWithText = function (container) {

    var anchor = null;

    container.find('a').each(function () {
        if ($(this).text()) {
            anchor = $(this);
            return false; // Exits from the loop as soon as the element is found
        }
    });

    return anchor;

}

Demo Fiddle here.

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

This complex selector first checks that the element does not have any children, then ensures that the element is not empty.

var anchor = $("a:not(:has(img)):not(:empty)").eq(0);

Working Example http://jsfiddle.net/dZLKE/3/

Upvotes: 2

Alvaro
Alvaro

Reputation: 41605

$('a').each(function(){
    if($.trim($(this).text()) != ''){
       alert($(this).text());
    }
});

Living demo: http://jsfiddle.net/AGKeY/2/

Upvotes: 0

Jayamurugan
Jayamurugan

Reputation: 1825

var txtEl;
$('a').each(function(i, el){
  var text = $(el).text();
  if(text != ""){
     txtEl = el;
     return false;
  }
});

Jquery Selector

Upvotes: 0

Blender
Blender

Reputation: 298206

jQuery doesn't have a lazy first selector, so you will still end up matching all of the anchor tags before filtering them:

$('a').filter(function() {
    return $(this).text();
}).first()

Upvotes: 2

Related Questions