Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get sibling element (div) in Javascript?

So I have this HTML:

<div class="tip-box">
    <div class="tip-title" onclick="toggleTip()">
        <h2>Tip 1</h2>
    </div>
    <div class="tip-content hidden">
        <p>Tip 1 content</p>
    </div>
</div>

And this Javascript:

function toggleTip() {
    $(this).siblings(".tip-content").toggleClass("hidden");
}

Hopefully it's obvious what this is supposed to do, but it doesn't work. Using .siblings() just doesn't seem to work in this way.

What's the correct solution for this? To get the next sibling of a certain type or with a certain class and then hide/show it?


2 Answers

You can use Jquery function.

<div class="tip-box">
    <div class="tip-title">
        <h2>Tip 1</h2>
    </div>
    <div class="tip-content hidden">
        <p>Tip 1 content</p>
    </div>
</div>

$(document).ready(function(){
    $('.tip-title').click(function(){
        $(this).siblings(".tip-content").toggleClass("hidden");
    });
});

you can also use this

<div class="tip-box">
    <div class="tip-title" onclick="toggloTip(this)">
        <h2>Tip 1</h2>
    </div>
    <div class="tip-content hidden">
        <p>Tip 1 content</p>
    </div>
</div>


<script>
function toggloTip(elm) {
    $(elm).siblings(".tip-content").toggleClass("hidden");
}
</script>
like image 155
Kamruzzaman Avatar answered Oct 30 '25 01:10

Kamruzzaman


You can use pure javaScript with nextElementSibling property of node something like below, I suppose you want do this operation with siblings.

function getChildrens(n, selector) {
  var nodes = [];
  while (n.nextElementSibling != null) {
    if (n.nextElementSibling.hasOwnProperty('classList')) {
      if (n.nextElementSibling.classList.contains(selector)) {
        //return n.nextElementSibling;
        nodes.push(n.nextElementSibling);
      }
    }
    n = n.nextElementSibling;
  }
  return nodes;
};

function getSiblings(n, selector) {
  return getChildrens(n, selector);
}

function toggleTip(elem) {
  var siblings = getSiblings(elem, "tip-content");
  if (siblings.length > 0) {
    for (var i = 0; i < siblings.length; i++) {
      siblings[i].classList.toggle("hidden");
    }
  }
}
.hidden {
  display: none;
}
<div class="tip-box">
  <div class="tip-title" onclick="toggleTip(this)">
    <h2>Tip 1</h2>
  </div>
  <div class="tip-content hidden">
    <p>Tip 1 content</p>
  </div>
</div>
like image 43
Suman Bogati Avatar answered Oct 30 '25 00:10

Suman Bogati