1

Using jQuery, I'm trying to target all paragraph elements that only contain a child anchor element (as a direct descendent) AND that have no text nodes outside of that child element, eg:

<p><a href="http://...">Some link</a></p>

I've tried jQuery's only-child selector, but text nodes obviously aren't treated as child elements. I've also looked at contents() and presume I could target anchor elements whose opening tag is the first node. However, on the latter, the site I'm building is a blog that others will be writing for using a CMS and so I can't ensure they won't begin a regular paragraph with a link, which would add unwanted styling.

I'm relatively new to jQuery - about one month. Just so you know...

Thanks!

lukebm
  • 163
  • 11
  • 1
    you could try using `.text().length` it return the length of a text inside an element and ignores HTML snippets (such as `""`). Combine this with a `$.each` loop and you can check every child node for its `text().length` – flx Sep 14 '15 at 12:14

2 Answers2

2

Working fiddle

$('p').filter(function() {
  return ( 1 === $(this).find('*').length && 1 === $(this).find('a').length && $(this).text() === $(this).find('a').text() );
});

Edit: I didnt know about the :only-child selector in the first place. With it, even cleaner:

$('p').has('a:only-child').filter(function() {
    return $(this).find('a').text() === $(this).text();                  
});
Alex
  • 9,911
  • 5
  • 33
  • 52
  • Thanks, Alex! This is exactly what I'm looking for. Reading through it a few times, it seems like such a clear, logical solution. Thanks again! – lukebm Sep 14 '15 at 14:03
1

Inspired by zeropublix comment:

$("p").has("a:only-child").filter(function() {
    return $(this).find("a").text() === $(this).text();                  
});

You could also prototype it to make your code cleaner:

$.fn.onlyChild = function(child) {
   return this.has(child + ":only-child").filter(function() {
        return $(this).find(child).text() === $(this).text();                  
    });
}

Working fiddle.

Anders
  • 8,307
  • 9
  • 56
  • 88
  • Many thanks, Anders. I need to grasp loops so will have a play around with this too. Cheers – lukebm Sep 14 '15 at 14:05