How can I get the neighbor of an html element in javascript?

Viewed 989

Sample html:

<div class="container" id="neighbor-color-div">
        <button id="change-neighbour-color" onclick="change_neighbor_color()">Change my 
        neighbour color!</button>
        <button id="neighbour">Click the other button!</button>
</div>
<script src="./main.js" defer></script>

Sample main.js:

function change_neighbor_color() {
 ...
}

I don't know how to do that, but after I click the "change-neighbor-color" id button the text color of the other button should change to blue.

Thank you for your help.

2 Answers

Generic way

You can pass at the function call a reference to the button which calls the function with this

 <button id="change-neighbour-color" onclick="change_neighbor_color(this)">

Then you have a reference to the called button element e.target;

  • Then get all your buttons with querySelectorAll()
  • loop through all the buttons and check at which index the btn which called the function is by comparing it's ID.
  • The best would be when your buttons you would like to involve have the same class names.

Then your neighbour will be the button at index +1

        function change_neighbor_color(e) {
           let index;
           let nodes = document.querySelectorAll(".btn");
           nodes.forEach((n, ind) => {
           if(n.id === e.id){
           index = ind;
           }
           })
           
           if(index !== undefined && index !== null){
              nodes[index+1].style.color = "blue";
            }else{
           console.log("NO NEIGHBOUR FOUND");
            }

 
            }
     <div class="container" id="neighbor-color-div">
                    <button id="change-neighbour-color" class="btn" onclick="change_neighbor_color(this)">Change my 
                    neighbour color!</button>
                    <button id="neighbour" class="btn">Click the other button!</button>
            </div>
            <script src="./main.js" defer></script>

Non Generic Way Access the neighbour element by it's id and give it the color blue with .style.color

document.getElementById("neighbour").style.color = "blue";

    
    function change_neighbor_color() {
document.getElementById("neighbour").style.color = "blue";
}
<div class="container" id="neighbor-color-div">
        <button id="change-neighbour-color" onclick="change_neighbor_color()">Change my 
        neighbour color!</button>
        <button id="neighbour">Click the other button!</button>
</div>
<script src="./main.js" defer></script>

function change_neighbor_color() {
 document.getElementById('neighbour').style.color= 'blue';
}
Related