There is a document in which div-blocks are added during the formation. I wanted to include the button "Show completely" in each such div-block, which would change the height of the block in which it was pressed from a fixed value to auto.

With the help of .getElementById I can do this, but here I cannot preset the unique identifiers for the blocks, since their total number formed by the external system is unknown.

That is, a structure, such as

function toggle() { var tBlock = document.getElementById("textblock"); var tText = document.getElementById("text"); if (tBlock.style.height === "100px" && tText.style.height === "60px") { tBlock.style.height = "auto"; tText.style.height = "auto"; } else { tBlock.style.height = "100px"; tText.style.height = "60px"; } } 
 .docText { height: 100px; width: 100px; background: green; margin-bottom: 5px; } .docTextContent { height: 60px; width: 100px; overflow: hidden; } 
 <div class="docText" id="textblock"> <div class="docTextContent" id="text"> Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn" onclick="toggle()">Показать</button> </div> <div class="docText"> <div class="docTextContent"> Много текста Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn">Показать</button> </div> <div class="docText"> <div class="docTextContent"> Много текста Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn">Показать</button> </div> 

How to make the button not work on id and reveal the text only in its block?

  • We need a cycle, right ... But not id , but a class and already on the element index to choose a specific block ... But it’s not at all clear what exactly you want to implement - Air

3 answers 3

 function toggle(obj) { var parentElement = obj.parentElement; var childElement = parentElement.firstElementChild; if (parentElement.style.height === "100px" && childElement.style.height === "60px") { parentElement.style.height = "auto"; childElement.style.height = "auto"; } else { parentElement.style.height = "100px"; childElement.style.height = "60px"; } } 
  <div class="docText"> <div class="docTextContent"> Много текста Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn" onclick="toggle(this)">Показать</button> </div> <div class="docText"> <div class="docTextContent"> Много текста Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn" onclick="toggle(this)">Показать</button> </div> 

     $(document).ready(function(){ $('.toggle_btn').on('click',function(even){ $('.docTextContent',even.target.parentNode).toggleClass('hidden'); }); }); 
      .docText { height: 100px; width: 100px; background: green; margin-bottom: 5px; } .docTextContent { height: 0px; width: 100px; overflow: hidden; } .hidden{ height: 70px; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="docText"> <div class="docTextContent"> Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn">Показать</button> </div> <div class="docText"> <div class="docTextContent"> Много текста Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn">Показать</button> </div> <div class="docText"> <div class="docTextContent"> Много текста Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn">Показать</button> </div> 

    Get hurt

      Use the querySelectorAll method to select all DOM elements corresponding to the selector. This method is standardly implemented in the Element and HTMLDocument . It returns a static NodeList : DOM collection, or more simply, an array-like list of nodes (elements).

      Note that NodeList not a “real” array — this type does not inherit Array and its enumeration methods (such as forEach , every , map , etc.).

      Found elements can be bypassed in a loop using the usual for , or for..of .


      In order for the button to hide its parent block, you can get this block through the parentElement property, and assign it a class with CSS styles.

      When writing a handler through a normal (non-pointer) function, this refers to the owner of this handler ... which means that you do not need to search for the parent element: just write this.parentElement .
      A class is easily and quickly added to an element through the classList property and its add method (but in this case, it is more appropriate to switch the class using the toggle method).


      Below is a sample code in the spoiler that demonstrates the above:

       document.addEventListener('DOMContentLoaded', () => { // копируем блок. это чисто для компактности примера кода cloneElmnt(document.querySelector('.doc-wrapper'), 2); // получаем все элементы кнопок, вешаем обработчик клика let btns = document.querySelectorAll('.doc-wrapper .toggle_btn'); for (let btn of btns) btn.addEventListener('click', onToggleClick); }); // обработчик очень простой - переключаем класс, для применения CSS function onToggleClick() { this.parentElement.classList.toggle('show'); } function cloneElmnt(el, count) { while (count-- > 0) el.parentElement.appendChild(el.cloneNode(true)); } 
       body { font: 16px sans-serif; } .container { height : 80px; padding: 4px; display: flex; justify-content: space-around; } .doc-text { width: 120px; height: 100%; background-color: #aea; text-align: center; } .doc-text-content { position: relative; height: calc(100% - 2em); /* минус высота пространства под кнопку */ overflow: hidden; } .toggle_btn { margin: 0.4em 0; } .toggle_btn:after { content: 'Показать'; } /* вот этот класс и описывает развернутый блок */ .show { height : auto; overflow: visible; /* отображение содержимого за пределами границ элемента */ z-index : 10; /* для отображения над элементами ниже контейнера */ position: relative; /* обеспечиваем контекст наложения (иначе z-order не будет работать) */ } .show .toggle_btn:after { content: 'Скрыть'; } 
       <div class="container"> <div class="doc-wrapper"> <div class="doc-text"> <div class="doc-text-content"> Много текста Много текста Много текста Много текста Много текста Много текста Много текста </div> <button class="toggle_btn"></button> </div> </div> </div> Безусловно, внедрение современных методик играет важную роль в формировании прогресса профессионального сообщества. Как уже неоднократно упомянуто, явные признаки победы институциализации могут быть смешаны с неуникальными данными до степени совершенной неузнаваемости, из-за чего возрастает их статус бесполезности. 

      As you probably noticed in the example, there is another similar method: querySelector (without "All"). It works in a similar way, except that it returns not a NodeList , but only one node — the first one that NodeList selector.

      • This is exactly what you need, but when you try to use something in the main project, something goes wrong. The button changes the name, but does not affect the block of text. Could this be due to the fact that the parameters of the css class .show overlap more specific selector? - Alexey Shevchenko
      • Be careful, I changed the markup (added a div wrapper) and class names (led them to the recommended notation). That is, if you simply copy the code without changes, it will not work, naturally ... correct it for your markup. ps: Overlap is also possible, of course. - yar85
      • Found the reason, did not replace the doc-wrapper with an analogue in my project. Thank you so much! - Alexey Shevchenko
      • Happy to help! :) By the way, if you need an introductory material on the modern capabilities of JS, it is well and clearly stated on learn.javascript.ru - I highly recommend it for reference. - yar85