Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

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

But if the <p> tag looks like this:

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

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

If a <p> tag only contains an <a> tag I want to add a certain class to the <a> tag.

I was using this code:

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

but this code only checks if the a-tag is the only child of the p-tag, not if it's the only content. This is where I'm currently stuck.

like image 902
tkahn Avatar asked Nov 13 '22 04:11

tkahn


1 Answers

It can be very easy with one selector:

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

Live DEMO

like image 110
gdoron is supporting Monica Avatar answered Dec 21 '22 04:12

gdoron is supporting Monica