检查父元素是否具有特定子元素

时间:2018-04-18 16:20:22

标签: javascript dom

我正在尝试编写一个脚本,该脚本将动态地将特定样式标记放在我的文档中的某些数字和符号周围,但我只希望该函数在我运行它的段落不包含任何内容时激活<img>,以及我选择的其他一两个标签。

有一种简单的方法可以测试吗?我现在尝试使用的方法似乎不起作用,因为我无法按照我需要的方式访问HTML集合。

const paragraphElements = document.getElementsByTagName("p");
const imgTags = /(IMG|img)/g;

for (var i = 0; i < paragraphElements.length; i++) {

 // children of paragraph elements
 let paragraphChildren = paragraphElements[i].children;

 // trying to access the array of children then test whether there are any img tags

 for (var h = 0; h < paragraphChildren.lengh; h++) {
   console.log(paragraphChildren[h].tagName); // displays nothing

 if (imgTags.test(paragraphChildren[h])) == false {

      // will add the styling code in here.

     }
    }
   }

对于如何做到这一点的任何建议表示赞赏!

2 个答案:

答案 0 :(得分:2)

如果您已经知道要在段落中选择哪些元素,则可以简化初始选择器。我使用span作为选择多个元素的示例。

const paragraphElements = document.querySelectorAll('p img, p span');

这将返回页面上任意img个元素中的所有spanp元素。

然后您可以循环选定的项目。

let toSelect = document.querySelectorAll('p img, p span');

toSelect.forEach(function(obj) {

  if (obj.tagName == 'IMG') {
    // Style your images
    obj.style.width = '25px';
    obj.style.height = '25px';
    obj.classList.add('test-class');
  } else if (obj.tagName == 'SPAN') {
    // Style your spans
    obj.style.color = 'red';
  }

});
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi cum ratione illum saepe quia, magnam fuga molestiae nostrum, consequuntur voluptates error perferendis. Repellat distinctio dolores explicabo aliquid, quod adipisci <span>tempora!</span></p>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nesciunt quo eius nisi fugit qui maiores dolores recusandae eaque aperiam magni? Nobis veniam repellendus ut laboriosam perferendis dicta ab necessitatibus provident! <img src="//placehold.it/50x50"></p>

答案 1 :(得分:2)

您可以在getElementsByTagName

上再次致电Paragraph elements
const paragraphElements = document.getElementsByTagName("p");

for (var i = 0; i < paragraphElements.length; i++) {
    let paragraphElement = paragraphElements[i];
    let images = paragraphElement.getElementsByTagName("img");
    if(!images.length > 0){
        // add your class here 
        paragraphElement.classList.add("yourClassName");
    }
}