-2

I want to retrieve the content of all textarea elements inside a particular div. Here is how I tried to iterate over them

var ta = document.getElementById('parent').getElementsByTagName('textarea')
ta.forEach(element => {
  console.log(element);
});

but I get

Uncaught TypeError: ta.forEach is not a function
    at HTMLButtonElement.<anonymous> (details:512)
    at HTMLButtonElement.dispatch (jquery.min.js:3)
    at HTMLButtonElement.r.handle (jquery.min.js:3)

Is this the proper way to get all textarea elements inside a particular div? I want to get the content of all of these textarea elements along with the name of the element. How can I do that?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
AbtPst
  • 7,778
  • 17
  • 91
  • 172

4 Answers4

3

getElementsByTagName returns HTMLCollection. It does not have the forEach method. Use the for loop as illsutrated in Element.getElementsByTagName().

var ta = document.getElementById('parent').getElementsByTagName('textarea');
for (let element of ta) {
  console.log(element);
}
Gosha_Fighten
  • 3,838
  • 1
  • 20
  • 31
  • 2
    Yeah, [but don't use `.getElementsByTagName()` at all](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474). – Scott Marcus Oct 17 '19 at 19:16
1

Use .querySelectorAll(), which allows for any valid CSS selector to be passed to it and it will return a collection of all matching elements. Then, loop over the results, but because IE doesn't support .forEach() on collections, you should convert it into a formal array before using .forEach().

And don't use .getElementsByTagName() (ever again).

// Get the textareas inside the div with an id of "target2"
let areas = document.querySelectorAll("#target2 textarea");

// Convert the collection into an array and loop over the array
Array.prototype.slice.call(areas).forEach(function(area){
  console.log(area.textContent);
});
<div id="target">
  <textarea>stuff</textarea>
</div>
<div id="target2">
  <textarea>stuff2</textarea>
  <textarea>stuff2a</textarea>
</div>
<div id="target3">
  <textarea>stuff3</textarea>
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
1

If you are just trying to get the content of the input or textarea, I think you could use .value to capture that and print it to console.

something like:

for (i = 0; i < document.getElementById('parent').getElementsByTagName('textarea').length; i++) {
  console.log(document.getElementById('parent').getElementsByTagName('textarea')[i].value)
}

editing since it HTML collection in fact does not work with .value

D-Money
  • 137
  • 1
  • 12
-1

You want something like this?(Write text and click outside)

document.getElementsByTagName('textarea')[0].onchange = function(){ console.log(document.getElementsByTagName('textarea')[0].value);
}
<textarea></textarea>
novruzrhmv
  • 639
  • 5
  • 13