[英]How to select element, enclose it in a div and add a class to it, in pure javascript?
Building a responsive site, the entries to the CMS are all all in markdown. 建立响应站点后,CMS的条目全部在减价中。 So not practical to code the div into the document in all the new entries.
因此在所有新条目中将div编码到文档中是不切实际的。 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. 我需要在帖子中选择一个
<img>
,然后用具有特定样式的div包装它。 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 我通过将图像周围的div硬编码到帖子中找到了解决方案
HTML HTML
<div class="imgWrap">
<img>
</div>
CSS 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 rel Javascript - 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. 我找到了这个相关的Javascript-如何将div类添加到createElement ,然后我跟随了链接,包括HTML DOM className属性 ,该属性帮助我启动了脚本,但对于下一步仍然感到困惑。
I am building this site in Ruby with Jekyll, in case there is a different way you suggest approaching this. 如果您建议采用其他方式,我将与Jekyll一起在Ruby中构建此网站。
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 for you. 这应该为您工作。
querySelector
works all the way back to IE8. querySelector
工作到IE8。
If there was the possibility for multiple <img>
tags, you could use document.querySelectorAll
and then loop through those and do the same manipulations: 如果可能有多个
<img>
标签,则可以使用document.querySelectorAll
然后遍历这些标签并执行相同的操作:
var imgs = document.querySelectorAll('div.post img');
for ( var i = 0, l = imgs.length; i < l; ++i ) {
var img = imgs[i];
var div = document.createElement('div');
div.className = 'imgWrap';
img.parentNode.insertBefore(div, img);
div.appendChild(img);
}
one way of doing it would be 一种方法是
var img = document.querySelector('div.post img');
var imgParent = img.parentNode;
var div = document.createElement('div');
div.className = 'imgWrap';
div.appendChild(img);
imgParent.appendChild(div);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.