JQuery If the "P" tag contains the "Img" tag, add the "Text Align Center" to the "P" tag

I just need a little help adding text center alignment to p tags if they contain an image. I need this to be able to center attached images in Wordpress. Thanks for any help you can offer!

+4
source share
4 answers

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

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

Alternatively, you can use the :has selector:

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

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

+10
source

Using jQuery:

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

Just because I ran it through JS Perf , I thought I would post a simple JS version (which in Chromium 14 / Ubuntu 11.04 is the fastest approach to solve 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 JS Fiddle .

Literature:

+2
source
 $('img').closest('p').css('text-align', 'center'); 
+1
source

Usage has: http://api.jquery.com/has/

 $('p').has('img').css('textAlign', 'center'); 
+1
source

Source: https://habr.com/ru/post/1387473/


All Articles