2

I have this html structure:

  <div id="xyz"> </div>
  <div class="content"> </div>

i want to hide the element with class named content given the sibling element id which is xyz , in jQuery i can easily do it like this:

$("#xyz").siblings('.content').css({"dispaly": "none"});

how can i achieve the same thing using pure Javascript only ?

Padawan
  • 103
  • 1
  • 7
  • Does this help https://gomakethings.com/finding-the-next-and-previous-sibling-elements-that-match-a-selector-with-vanilla-js/? – Tushar Shahi Jul 01 '21 at 04:27

4 Answers4

4
document.querySelector("#xyz + .content").style.display = "none";

jsfiddle

Chris Wong
  • 564
  • 4
  • 4
2
document.getElementById("xyz").nextElementSibling.style.display = 'none';
  • 2
    While this code may answer the question, providing additional context regarding *how* and/or *why* it solves the problem would improve the answer's long-term value. – Sven Eberth Jul 01 '21 at 22:13
0

try like this:

var x = document.getElementById("xyz").nextSibling;
while(true){   
   if(typeof(x) === "undefined"){
      break;
   }else if( x.className === "content"){
      x.style.display = 'none';
   }

   x = x.nextSibling;
}

Sorry, this code i still not testing yet.

Lý Hoài
  • 129
  • 6
0

what about just

document.getElementsByClassName("content")

u can use it like

document.getElementsByClassName("content")[0].style.display = "none"
Bertu
  • 1
  • 1
  • 1
    While the following code might produce the same desired output. It is not the direct answer to the problem presented by the question (i.e. How to use the class name of an element to select it's sibling with a given class name?). The above solution only satisfies a specific html content and will fail on a different structure that may have the same requirements. – Alex Pappas Dec 20 '22 at 11:16