如何判断子元素含特定文本时不执行insertAdjacentHTML插入?
原生JavaScript解决方案
直接修改你的代码,添加文本检查逻辑即可,分两种常见场景:
场景1:检查.product-item-info下所有内容是否包含特定文本
如果只要该元素及其子元素的文本里存在目标内容,就跳过插入:
const descriptions = document.querySelectorAll(".product-item-info"); // 定义要检查的特定文本 const targetText = "需要匹配的文本"; function showDescription() { descriptions.forEach(description => { // 检查当前元素的文本内容是否不包含目标文本 if (!description.textContent.includes(targetText)) { description.insertAdjacentHTML("beforeend", "<div class='description'>Some text</div>"); } }); } showDescription();
场景2:只检查.product-item-info下的特定子元素是否包含文本
如果只需要检查某个指定子元素(比如类名为.product-name的元素)的文本:
const descriptions = document.querySelectorAll(".product-item-info"); const targetText = "需要匹配的文本"; function showDescription() { descriptions.forEach(description => { // 找到目标子元素,可选链操作符避免找不到元素时报错 const targetElement = description.querySelector(".product-name"); // 如果子元素不存在,或者子元素文本不包含目标内容,才执行插入 if (!targetElement || !targetElement.textContent.includes(targetText)) { description.insertAdjacentHTML("beforeend", "<div class='description'>Some text</div>"); } }); } showDescription();
关键说明
textContent会获取元素下所有文本内容(包括隐藏元素),如果需要只获取可见文本,可以用innerText替代。includes()方法是大小写敏感的,如果需要忽略大小写,可以把两边文本都转成小写/大写后再判断:!description.textContent.toLowerCase().includes(targetText.toLowerCase())
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

