Syntax getElementByTagName()
document.getElementByTagName(tagname);
The method takes a string parameter as tagname. For example, getElementByTagName('textarea') for textarea elements or getElementByTagName('input'), in case you want to get all input boxes from your web form.
Note: The method’s parameter is not case sensitive. That is, it can be textarea or Textarea. However, just make sure that you pass the string parameter (the tag name) as it is.
Let’s see an example. Here’s my form with few textarea elements.
<body> <div> <!--I have three textarea elements.--> <ul> <li><textarea id="a1"></textarea></li> </ul> <ul> <li><textarea id="a2"></textarea></li> </ul> <ul> <li><textarea id="a3"></textarea></li> </ul> </div> <p> <input type="text" id="txt1" placeholder='Enter your name'> <input type="button" id="bt1" value='Submit' onclick='getTArea()'> </p> </body>
Along with textarea, I have two input boxes of type text and button. I only want to extract the textareas and its values.
<script>
let getTArea = () => {
const ele = document.getElementsByTagName('textarea');
for (let i = 0; i <= ele.length - 1; i++) {
if (ele[i].value != '')
alert (ele[i].value);
else {
alert ('Enter some value in textarea');
return false;
}
}
}
</script>
The getElementsByTagName() method will return an HTMLCollection of elements with the <textarea> tag. See this result in your browser’s console window.
let ele = document.getElementsByTagName('textarea');
console.log(ele);
Finally, you can loop through each element and get the values from it. I have used a for loop in the above example to extract values from the elements. You may also use this method …
for (let el of ele) { console.log (el); // or console.log (el.value); }