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.

janos
113k15 gold badges154 silver badges396 bronze badges
asked Oct 22, 2014 at 21:00
\$\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\$ 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"); 
answered Oct 23, 2014 at 15:32
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.