Javascript DOM HTML Node previousSibling Property get previous element

Description

Javascript DOM HTML Node previousSibling Property get previous element

View in separate window

<!DOCTYPE html> 

<html lang="en"> 
<head> 
    <title></title> 
</head> //www.j a  v a  2  s.c o m
<body> 
    <h1 id="heading1">My Heading</h1> 
    <p id="paragraph1">This is some text in a paragraph</p> 
    <script> 
        let pElement = document.getElementById("paragraph1"); 
        pElement.style.color = "red"; 

        let h1Element; 

        if (pElement.previousSibling.nodeType == 1) { 
            h1Element = pElement.previousSibling; 
        } else { 
            h1Element = pElement.previousSibling.previousSibling; 
        } 
        h1Element.style.color = "red"; 
    </script> 
</body> 
</html> 



PreviousNext

Related