There is such a code for tabs

<!DOCTYPE html> <html> <head> <title>Untitled</title> <meta charset="utf-8"> <style type="text/css"> div p { display: none; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script> $(function() { var div = $('div'); div.on('click', 'a', function(event) { event.preventDefault(); var parent = $(this).parent(); $('p',parent).show(); div.not(parent).find('p').hide() }) }); </script> </head> <body> <!--первый элемент--> <div> <a href="#">link-1</a> <p>text</p> </div> <!--второй элемент--> <div> <a href="#">link-2</a> <p>text</p> </div> <!--третий элемент--> <div> <a href="#">link-3</a> <p>text</p> </div> </body> </html> 

I'm trying to remake it in pure JS, but it does not work. Why when you click again, the tab does not close?

 var div2 = document.querySelectorAll('div'); for(var i = 0; i < div2.length; i++){ div2[i].addEventListener('click', function(event) { event.preventDefault(); if(event.target.nextElementSibling.style.display = 'none'){ event.target.nextElementSibling.style.display = 'block' } else if(event.target.nextElementSibling.style.display = 'block'){ div2[i].lastElementChild.style.display = 'none' } }) //div2[i].lastElementChild.style.display = 'none' } 
  • and what is the reason for the rejection of jQuery, if not a secret? - teran
  • on the subject in jquery, your handler hangs on the link click, and hides the p tags, and something I don’t really see in your JS code. - teran
  • one
    If I use ready-made solutions, I will not learn anything like that - DivMan

1 answer 1

 var div2 = document.querySelectorAll('div p'); var div_a = document.querySelectorAll('div a'); cloaseall(null) function cloaseall(item) { div2.forEach(function(el) { el.classList.add("noactive") }) if (item) { item.parentNode.children[1].classList.remove("noactive"); } } for (var i = 0; i < div_a.length; i++) { div_a[i].addEventListener('click', function(event) { event.preventDefault(); cloaseall(this); }) } 
 .noactive { display: none; } 
 <!--первый элемент--> <div> <a href="#">link-1</a> <p>text</p> </div> <!--второй элемент--> <div> <a href="#">link-2</a> <p>text</p> </div> <!--третий элемент--> <div> <a href="#">link-3</a> <p>text</p> </div> 

  • And what is cloaseall? Google does not give anything in Russian - DivMan
  • because this is what I thought now ....)))) - C.Raf.T
  • I realized this is the launch of the function - DivMan
  • Yes. At the beginning, everyone should be closed, I understand ... - C.Raf.T