【问题标题】:Select element only if it is immidiatly followed by another element仅当元素紧跟着另一个元素时才选择元素
【发布时间】:2023-03-27 04:48:01
【问题描述】:

在 JavaScript 中,如果我使用 getElementsByTagName("li"); 获取所有 li 元素那么我如何只选择紧跟 span 的 li 元素?例如:

<ul>
  <li>test<span style="color: red;"> A</span>dfg</li>
  <li><span style="color: red;">Test B</span>dfg</li>
</ul>

这里我只想选择第二个 li,因为它紧随其后的是 span,而不是第一个,因为它以文本打开。

【问题讨论】:

  • 我认为您需要使用document.querySelectorAll('li .class span') 获取元素,如果您选择第二个元素。第二节课

标签: javascript html


【解决方案1】:

下面的函数收集一个 li 元素(无论你如何获取该元素),并检查它的第一个子元素是否是一个跨度并返回它

function checkElem(elem) {
    // check if the element is an li element
    if (elem.tagName != "LI") {
        // if its not, return false
        console.log("The element passed is not an li element");
        return false;
    } else {
        // get the first child element of the li
        var firstChild = elem.firstChild;

        // check if the first child is a span tag
        if (firstChild.tagName == "SPAN") {
            // return the li element
            return elem;
        } else {
            // else return false
            console.log("List item's first element is not a span");
            return false;
        }
    }
}

所以你可以这样使用

var liElements = getElementsByTagName("li");

liElements.forEach(li => {
    var myLi = checkElem(li);
    
    if(myLi != false){
        myLi.style.fontSize = "30px";
    }
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-13
    • 2022-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-20
    • 1970-01-01
    相关资源
    最近更新 更多