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

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


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:


$('img').closest('p').css('text-align', 'center');