Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery If "P" tag contains "Img" tag add "Text Align Center to "P" tag

I just need a bit of help adding a text align of center to p tags if they contain an image. I need this to be able to center attached images within wordpress. Thank you for any and all help you may be able to offer!

like image 974
Brock Avatar asked Dec 09 '22 03:12

Brock


2 Answers

You can use has to narrow down the set of all p elements to those which contain img elements, and then use css to change the property:

$("p").has("img").css({textAlign: "center"});

Alternatively, you could use the :has selector:

$("p:has(img)").css({textAlign: "center"});

However, the .has method is faster than the selector.

like image 194
James Allardice Avatar answered Feb 13 '23 04:02

James Allardice


With jQuery:

$('p:has("img")').css('text-align','center');

Just because I ran this through JS Perf, I thought I'd post a plain JS version (that, in Chromium 14/Ubuntu 11.04, is the fastest approach to solving the problem):

var imgs = document.getElementsByTagName('img');
for (var i=0,len=imgs.length; i<len; i++){
    if (imgs[i].parentNode.tagName.toLowerCase() == 'p'){
        imgs[i].parentNode.style.textAlign = 'center';
    }
}

Along with a JS Fiddle.

References:

  • css().
  • :has().
like image 35
David Thomas Avatar answered Feb 13 '23 04:02

David Thomas