var textareas = document.querySelectorAll('textarea'); textareas.forEach(function(item) { item.addEventListener("focus", function() { var idNum = this.id.split('-')[1]; document.querySelector('#otvbl-' + idNum).style.display = 'block'; }, true); });
<textarea id="divid-1"></textarea> <div style="display:none;" id="otvbl-1"> text </div> <br/> <textarea id="divid-2"></textarea> <div style="display:none;" id="otvbl-2"> text2 </div> <br/> <textarea id="divid-3"></textarea> <div style="display:none;" id="otvbl-3"> text3 </div>
So that js loaded after everything has been loaded, you can wrap it in DOMContentLoaded :
document.addEventListener("DOMContentLoaded", function(event) { var textareas = document.querySelectorAll('textarea'); textareas.forEach(function(item) { item.addEventListener("focus", function() { var idNum = this.id.split('-')[1]; document.querySelector('#otvbl-' + idNum).style.display = 'block'; }, true); }); });
In general, at least, in order not to produce as many IDs, you just need to make a wrapper, in which there will be both a textarea and a div. And when you press the focus of textiles, take a div in the same wrapper as textarea. Then it will be much easier
something like:
// document.addEventListener("DOMContentLoaded", function(event) { var textareas = document.querySelectorAll('textarea'); textareas.forEach(function(item) { item.addEventListener("focus", function() { // this.closest('.wrap').querySelector('textarea+div').style.display = 'block'; this.closest('.wrap').children[1].style.display = 'block'; }, true); }); // });
.wrap > div { display: none; }
<div class="wrap"> <textarea></textarea> <div> text </div> </div> <div class="wrap"> <textarea></textarea> <div> text2 </div> </div> <div class="wrap"> <textarea></textarea> <div> text3 </div> </div>
C Jquery even easier :)