繁体   English   中英

如果子元素包含特定文本,如何插入相邻元素?

[英]How to insert an adjacent element if child element contains specific text?

我正在使用以下代码插入一个元素:

var descriptions = document.querySelectorAll(".product-item-info");

function showDescription() {
  descriptions.forEach(description => {
      description.insertAdjacentHTML("beforeend", "<div class='description'>Some text</div>");
   
  });
}

showDescription();

这很好用。 但是我如何检查.product-item-info的子元素是否包含特定文本,如果是,则不将标记添加到所述元素?

我知道如何使用 jQuery 执行此操作。

编辑:将afterend更改为beforeend

您使用 DOM 执行此操作的方式与使用 jQuery 的方式相同,只是您必须执行 jQuery 在您自己的代码中在幕后执行的操作:查看元素是否包含该文本。 没有真正的捷径,您只需要查看元素的文本:

const descriptions = document.querySelectorAll(".product-item-info");

function showDescription() {
    for (const description of descriptions) {
        if (!description.textContent.includes("Some text")) {
            description.insertAdjacentHTML("beforeend", "<div class='description'>Some text</div>");
        }
    }
}

showDescription();

(可选链接处理描述没有下一个元素兄弟的情况。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM