To get the sibling element of an HTML element using JavaScript, you can use the nextElementSibling
and previousElementSibling
properties. Here’s how you can retrieve the sibling elements:
1. Get the next sibling element:
var element = document.getElementById('yourElementId');
var nextSibling = element.nextElementSibling;
2. Get the previous sibling element:
var element = document.getElementById('yourElementId');
var previousSibling = element.previousElementSibling;
Note: these properties return null
if there are no sibling elements, so make sure to handle such cases accordingly.
Get sibling element JavaScript example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<title>Get Sibling Element Example</title>
</head>
<body>
<div id="parent">
<div id="sibling1">Sibling 1</div>
<div id="target">Target Element</div>
<div id="sibling2">Sibling 2</div>
</div>
<script>
var targetElement = document.getElementById('target');
// Get the next sibling element
var nextSibling = targetElement.nextElementSibling;
console.log('Next Sibling:', nextSibling);
// Get the previous sibling element
var previousSibling = targetElement.previousElementSibling;
console.log('Previous Sibling:', previousSibling);
</script>
</body>
</html>
Output:
When you run the example and check the browser console, you will see the logged output with the next and previous sibling elements.
Comment if you have any doubts or suggestions on this Js element topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version