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!
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.
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()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With