I found a javascript function that I want to apply to all targeted elements, in my case all textarea from page but when I am changing the selector from document.getElementById('text');
into document.querySelectorAll('textarea');
or document.getElementsByTagName('textarea')
in order to target all elements is not working and I don't understand why, I have tried to put text
variable in a for
but still not working, if someone can help me a little bit with this dummy issue :|
Asked
Active
Viewed 78 times
0

Community
- 1
- 1

RulerNature
- 693
- 4
- 13
- 40
-
So to summarize: You have understood that `getElementsByTagName` returns a list of items. You have understood that you need some sort of loop to go through them one by one. You have half-heartedly tried to use a `for` loop. You have **not** looked at any documentation or examples of `for` loops. You have **not** tried for longer than 10 minutes. – Tomalak May 06 '15 at 06:45
1 Answers
1
You were on the right track with a loop, you just didn't go far enough (see comments):
function init () {
var list, i, text;
// Get the list
list = document.getElementsByTagName('textarea');
// Loop through it
for (i = 0; i < list.length; ++i) {
// Get this entry
text = list[i];
// Do things with it
observe(text, 'change', resize);
observe(text, 'cut', delayedResize);
observe(text, 'paste', delayedResize);
observe(text, 'drop', delayedResize);
observe(text, 'keydown', delayedResize);
// Initial `resize` call -- I'm using `.call` in order to
// set `this` to the element during the call, like an event
// does
resize.call(text);
// You'll have to choose *one* of them to focus; I chose the first
if (i == 0) {
text.focus();
text.select();
}
}
function resize () {
// Note that I'm using `this` here, not `text` or `list`
// `this` will refer to the element the event is occurring on
this.style.height = 'auto';
this.style.height = this.scrollHeight+'px';
}
// 0-timeout to get the already changed text
function delayedResize () {
// Again note the use of `this`, also `.bind`.
// `Function#bind` creates a function that, when called,
// calls the original with a specific `this` value
window.setTimeout(resize.bind(this), 0);
}
}

T.J. Crowder
- 1,031,962
- 187
- 1,923
- 1,875
-
@T.J. Crowder, Can we dot it as jquery applies the event binding on all elements using some class-name ?? – Language Lassi May 06 '15 at 07:21
-
@openandfree: jQuery basically does a loop over matched elements. If you want to find elements matching a class (or any other CSS selector), you can use `document.querySelector("selector here")`. – T.J. Crowder May 06 '15 at 07:25