2
\$\begingroup\$

I want to add a class to only those <p> elements that have an <img>. So far this is what I have, it works, but I don't think I'm doing it right.

$(".entry-content p img").addClass(function(){
    $(this).parent("p").addClass("no-orphans-ctnr");
});

Here's a Demo/fiddle.

As you can see, I used the .addClass() method twice. I'm not a jQuery/JavaScript developer but that doesn't look right to me. Please review and help me improve it.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ The question seems to be how you can find a P tag whose ancestor is of class .entry-content and which has an IMG tag as a child. Or how to redo this without the outer addClass function: $(".entry-content p img").parent("p").addClass("no-orphans-ctnr"); Either would seem to be off-topic for Code Review: questions about code not yet written. \$\endgroup\$
    – Brythan
    Commented Oct 22, 2014 at 21:33
  • \$\begingroup\$ @Brythan, that worked :). I must've been too tired to not have figured out how simple it really was. Thanks! Yes, it was more the second. Not sure how they would be off-topic for Code Review if that's exactly what I needed help with: review my code. For code not written yet SO of course. If you type a separate answer, I'll chose it as the selected answer. Thanks again man! \$\endgroup\$ Commented Oct 23, 2014 at 3:01

1 Answer 1

3
\$\begingroup\$

To select the p elements that have an img as child element, you can use the p:has(> img) selector, like this:

$(".entry-content p:has(> img)").addClass("no-orphans-ctnr"); 
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.