Check if the child is the only content of the parent using jQuery

I need to check if the link (a-tag) is the only content (and not just the only child) inside the paragraph tag (p). Therefore, if the p-tag looks like this:

<p>Here we have some text inside the p-tag. Then there <a href="#">link</a>.</p> 

The <a> tag is not the only content inside the p-tag, since there is also text there.

But if the <p> looks like this:

 <p><a href="#">Nothing but a link inside this p-tag</a></p> 

the only content inside the <p> is the link.

If the <p> tag contains only the <a> tag, I want to add a specific class to the <a> tag.

I used this code:

 $("#MainColumn pa:only-child").addClass("singleLink"); 

but this code checks to see if only the a tag is the only p-tag tag, and not the only content . That's where I'm stuck right now.

+4
source share
4 answers

With one selector can be very easy:

 var $content = $("#MainColumn p:has(a)").filter(function() { return $(this).contents().length === 1; }).children('a').addClass("singleLink"); 

Live demo

+1
source

try the following:

  $('#MainColumn p a').each(function(){ var p = $(this).parent().text().length; var s = $(this).text().length; if (p == s) { $(this).addClass('singleLink') } }) 

http://jsbin.com/ewoqoy/2/

+1
source

I think it will be what you exclude

 String.prototype.startsWith = function(prefix) { return this.indexOf(prefix) === 0; } String.prototype.endsWith = function(suffix) { return this.match(suffix+"$") == suffix; }; var html = $("#myP").html(); if($("#myP p:only-child")){ if(html.startsWith("<p>") && html.endsWith("</p>")){ alert("hi"); } } <div id="myP"><p >Sample Text inside a <b>p</b> element</p></div> 
+1
source

Hmm ... maybe you can check if the content starts with "http: //" or "www":

 if($("#MainColumn pa:only-child").text().indexOf("www") != -1 { } 

Since your link is also “content”, you cannot distinguish between “your content” and “without content”. You must tell how your content is determined.

-2
source

All Articles