HTML - DOM 元素 nextElementSibling 屬性



nextElementSibling 屬性提供特定元素序列中緊鄰的下一個節點。它跳過不是元素的節點,例如文字或註釋節點。

語法

element.nextElementSibling

返回值

nextElementSibling 屬性返回一個包含給定元素的下一個兄弟節點的節點。如果不存在下一個兄弟節點,則返回“null”。

HTML DOM 元素“nextElementSibling”屬性示例

以下是一些示例,展示了“nextElementSibling”屬性的使用,以便更好地理解。

訪問和顯示下一個兄弟元素

此示例演示如何使用 nextElementSibling 節點訪問有關下一個兄弟節點的資訊,在本例中為<div>,並在應用突出顯示類後顯示其內容。

<!DOCTYPE html>
<html lang="en">
<head> 
    <style>
        .highlight {
            color: red;
        }
    </style>
</head>

<body>
    <h1>HTML - DOM Element</h1>
    <h2>nextElementSibling Property</h2>
    <p>Below are the contents of the parent element:</p>
    <div id="parent">
        <p>First paragraph</p>
        <div>Second div</div>
        <span>Span element</span>
        <p>Last paragraph</p>
    </div>

    <div id="output"></div>

    <script>
        // Accessing nextElementSibling
        const firstParagraph = document.querySelector
        ('#parent p');  
        const nextElement = firstParagraph.nextElementSibling;

        const outputDiv = document.getElementById('output');
        outputDiv.innerHTML = `Next sibling element found:
            <span class="highlight">${nextElement.textContent}
            </span>`;        
    </script>
</body>

</html>        

處理沒有下一個兄弟節點的情況

此示例演示如何使用 nextElementSibling 屬性處理給定元素沒有下一個兄弟元素的情況。

<!DOCTYPE html>
<html lang="en">
<head> 
    <title>nextElementSibling Example</title>
</head>
<body>
    <h1>HTML - DOM Element</h1>
    <h2>nextElementSibling Property</h2>
    <p>Below are the contents of the parent element:</p>
    <div id="parent">
        <p>First paragraph</p>
    </div>
        
    <div id="output"></div>

    <script>
        // Accessing Sibling when no next sibling exists
        const fp = document.querySelector('#parent p');
        const nextEle = fp.nextElementSibling;

        if (nextEle) {
            document.getElementById('output').textContent
            = `Next sibling element found: 
            ${nextEle.textContent}`;
        } else {
            document.getElementById('output').textContent
            = 'No next sibling element found.';
        }
    </script>
</body>

</html>       

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
nextElementSibling
html_dom_element_reference.htm
廣告