<script language="JavaScript"> function show_hide_all() { var obj = document.getElementById("comments"); if (obj.style.display == "none") obj.style.display = ""; else obj.style.display = "none"; return false; } </script> <span onClick="return show_hide_all()" class='precommets'>Комментарии</span> 

I need 3 such elements (comments), so as not to write the entire script 3 times, can I add 2 more elements to the show_hide_all function?

    1 answer 1

    If you have several elements with the same identifier in the html code, it is not necessary that document.getElementById("lolId") will not return an array, javascript has no idea that you do not know that several elements with the same identifier should not be. Rewrite the id attribute on the class attribute, then you can just do something like this, so do "good":

      <script type="text/javascript"> onload = function() { // pure js function changeDisplay() { if (obj.style.display == "none") obj.style.display = ""; else obj.style.display = "none"; return false; } var comments = document.getElementsByClassName('comments'); // тогда можно будет пробежаться по всем элементам в цикле for( var i=0; i<comments.length; ++i ) { var obj = comments[i]; obj.onclick = changeDisplay; } } </script> <script type="text/javascript"> // prototype version =) Event.observe(window,"load", function(){ function changeDisplay() { if (obj.style.display == "none") obj.style.display = ""; else obj.style.display = "none"; return false; } $$(".comments").each(function(el){ el.onclick = changeDisplay; // или Event.observe(el, "click", changeDisplay); }) }) </script> 

    Well, or just rewrite the function

      // тогда не обязательно переписывать идентификаторы // но надо понимать что несколько элементов с одинаковыми `id` // это бред! function changeDisplay() { if (this.style.display == "none") this.style.display = ""; else this.style.display = "none"; return false; } 

    If I understand the task correctly, if, when clicked, it is necessary to change the display of all elements:

      function changeDisplay() { var comments = document.getElementsByClassName('comments'); // тогда можно будет пробежаться по всем элементам в цикле for( var i=0; i<comments.length; ++i ) { var obj = comments[i]; obj.onclick = changeDisplay; } } 
    • What you need! Thank!!! - doove
    • accept the answer - green tick =) - Zowie