You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript为父div奇偶子元素内的img标签修改align属性?

解决父div奇偶子元素中img标签align属性的设置问题

之前遇到无法为父div的奇偶子元素修改内部img标签align属性的问题,查阅资料未找到可行方案,最终自行实现了解决方案。

实现代码

const children = document.getElementById('parent').children;
for (var i = 0; i < children.length; i++) {
    let newImg = children[i].children[2];
    if (i % 2 === 0) {
        newImg.align = "left";
        console.log(newImg.attributes.align); // 控制台查看输出
    } else {
        newImg.align = "right"; // 修正原代码中的变量名笔误:newsImg → newImg
        console.log(newImg.attributes.align); // 控制台查看输出
    }
}

说明

  • 通过document.getElementById('parent').children获取目标父div下的所有直接子元素
  • 遍历子元素时,根据索引的奇偶性(索引从0开始,偶数对应第1、3、5...个子元素)设置对应img的align属性
  • 代码中children[i].children[2]是取每个子元素下的第3个元素(索引从0计数)作为目标img,需根据实际DOM结构调整该索引值
  • 原代码的else分支存在变量名笔误(newsImg应为newImg),已修正避免运行报错

内容的提问来源于stack exchange,提问作者Amit Singh Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 01:40:23