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:
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.
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
.That would make
kids
a NodeList that your loop code should work with. You could even take it a step further and letquerySelectorAll
do the work of finding the paragraphs containing images: