html - How to select element, enclose it in a div and add a class to it, in pure javascript? -
building responsive site, entries cms all in markdown. not practical code div document in new entries. need add classes dynamically.
i need select <img>
within post wrap div has class style it. otherwise original width of image throws off layout.
i found solution hardcoding post div around image
html
<div class="imgwrap"> <img> </div>
css
.imgwrap { margin: 0 auto 18px; width: 100%; } .imgwrap img { max-width: 96%; }
but needs happen dynamically. 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 reljavascript - how add div class createelement , followed links, including html dom classname property helped me start script, still confused next step.
i building site in ruby jekyll, in case there different way suggest approaching this.
var img = document.queryselector('div.post img'); var div = document.createelement('div'); div.classname = 'imgwrap'; img.parentnode.insertbefore(div, img); div.appendchild(img);
this should work you. queryselector
works way ie8.
if there possibility multiple <img>
tags, use document.queryselectorall
, loop through , same manipulations:
var imgs = document.queryselectorall('div.post img'); ( var = 0, l = imgs.length; < l; ++i ) { var img = imgs[i]; var div = document.createelement('div'); div.classname = 'imgwrap'; img.parentnode.insertbefore(div, img); div.appendchild(img); }
Comments
Post a Comment