Building a responsive site, the entries to the CMS are all all in markdown. So not practical to code the div into the document in all the new entries. So need to add classes dynamically.
I need to select an <img>within the post then wrap it with a div that has a certain class to style it. Otherwise the original width of the image throws off the layout.

I found the solution by hardcoding into the post a div around the image
HTML
<div class="imgWrap">
<img>
</div>
CSS
.imgWrap {
margin: 0 auto 18px;
width: 100%;
}
.imgWrap img {
max-width: 96%;
}
But this needs to happen dynamically. I tried
<script>
var x=document.getElementsByTagName('div.post img')[0];
document.write("<div class="imgWrap">");
document.write("<img>");
document.write("</div>");
</script>
I had found this relJavascript - How to add div class to createElement And then I followed the links, including HTML DOM className Property which helped me start the script, but still confused as to the next step.
I am building this site in Ruby with Jekyll, in case there is a different way you suggest approaching this.