Plain JS: make 80% width element 100% IF contains an image

In my wordpress posts I want the text paragraphs to be 80% width but the images to be 100% width of the content area. However the images are wrapped in <p> tags so I want to write a little script that finds all the p tags in a post, and if any contains an img element – give the p tag a class that is specified 100% width in the CSS.

I found a way to do it with getElementByID:

Read More
    var kids = document.getElementById('content').getElementsByTagName('p');

    var looper = function(t){
    for(i=0; i<kids.length; i++){
      if(t[i].firstChild.tagName === "IMG"){
        t[i].setAttribute("class", "postimg");
      }
    }
    };

looper(kids);

Here is the jsbin: http://jsbin.com/meculi/

I am not sure how best to proceed when the content area has a class but no id the getElementsByTagName cannot be a method of getElementsByClassName.

Related posts

1 comment

  1. getElementsByClassName returns an array-like list of elements, so you can’t call element methods on its results. You can loop through the results and run your loop for each one, but I’d suggest a simpler solution: querySelectorAll.

    var kids = document.querySelectorAll('.content p');
    

    That would make kids a NodeList that your loop code should work with. You could even take it a step further and let querySelectorAll do the work of finding the paragraphs containing images:

    var paragraph_images = document.querySelectorAll('.content p > img');
    
    for (var i = 0; i < paragraph_images.length; i++) {
        paragraph_images[i].parentNode.className += ' postimg';
    }
    

Comments are closed.