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!

Related posts

Leave a Reply

4 comments

  1. 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.

  2. 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: