javascript - 普通 JS : make 80% width element 100% IF contains an image

标签 javascript wordpress dom width

在我的 WordPress 帖子中,我希望文本段落的宽度为内容区域的 80%,但图像的宽度为内容区域的 100%。然而,图像被包裹在 <p> 中。标签,所以我想编写一个小脚本来查找帖子中的所有 p 标签,如果有的话包含 img 元素 - 为 p 标签提供一个在 CSS 中指定 100% 宽度的类。

我找到了一种使用 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);

这是 jsbin:http://jsbin.com/meculi/

当内容区域有类但没有 id getElementsByTagName 时,我不知道如何最好地继续进行不能是 getElementsByClassName. 的方法

最佳答案

getElementsByClassName 返回一个类似数组的元素列表,因此您无法对其结果调用元素方法。您可以循环遍历结果并为每个结果运行循环,但我建议一个更简单的解决方案: querySelectorAll .

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

这将使 kids 成为循环代码应该使用的 NodeList。您甚至可以更进一步,让 querySelectorAll 完成查找包含图像的段落的工作:

var paragraph_images = document.querySelectorAll('.content p > img');

for (var i = 0; i < paragraph_images.length; i++) {
    paragraph_images[i].parentNode.className += ' postimg';
}

关于javascript - 普通 JS : make 80% width element 100% IF contains an image,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37104384/

相关文章:

linux - 服务器权限问题,我不能再在wordpress中上传文件

wordpress - 我可以在Wordpress中使用Contact Form 7插件获得条件字段吗?

php - 以编程方式添加带有附件的 Wordpress 帖子

javascript - 当元素在其下方动态移动时,光标样式不会更新

javascript - 什么是 "out of DOM"元素?

javascript - React - 设置状态

javascript - 如何使用对象(而不是数组)将 orderBy 和过滤器与 ng-repeat 一起使用?

javascript - 尝试从不同邮政编码获取推文时出现问题

javascript - Gulp:编译 Mustache 时避免中间文件

javascript - 具有递归更新的 JavaScript 中的 TreeView