None
None

Reputation: 9247

Resize textarea automatically?

I have this part of code :

let o = document.getElementById("name");
        let a  = document.getElementById('customerstype');
        let p = document.getElementById("parent");
        let h  = document.getElementById('hierarchy');
        let s  = document.getElementById('status');
        o.style.height = (o.scrollHeight - 10)+"px";
        a.style.height = (a.scrollHeight - 10)+"px";
        p.style.height = (p.scrollHeight - 10)+"px";
        h.style.height = (h.scrollHeight - 10)+"px";
        s.style.height = (s.scrollHeight - 10)+"px";

And for every textarea i have i need to say document.getElementyById. Is there any other way to do this and not to have 10lines of code, but to have unique for every textarea.

Upvotes: 0

Views: 97

Answers (4)

Marco Luzzara
Marco Luzzara

Reputation: 6026

You can use document.getElementsByClassName('class_name')(if your textAreas have a common class) or document.getElementsByTagName('tag_name'). These function return a NodeList object, but you can think of it as an array of DOM elements, on which you can use style property. Like others have said, the quickest way to set the style property on all of these elements is using a for loop ( or better a foreach loop).

Upvotes: 0

mt eee
mt eee

Reputation: 90

function check(t){ 
  t.style.height = (t.scrollHeight - 10)+"px";
}
textarea{
  height: 200px;
}
<textarea id="name" onkeydown="check(this)"></textarea>
<textarea id="customerstype" onkeydown="check(this)"></textarea>
<textarea id="parent" onkeydown="check(this)"></textarea>
<textarea id="hierarchy" onkeydown="check(this)"></textarea>
<textarea id="status" onkeydown="check(this)"></textarea>

I don't quite understand you demand, but i hope this can be helpful

Upvotes: 1

RahulB
RahulB

Reputation: 2110

Use class as I mentioned in comments like this --

<textarea id="name" class="myTextArea"></textarea>
<textarea id="customerstype" class="myTextArea"></textarea>
<textarea id="parent" class="myTextArea"></textarea>
<textarea id="hierarchy" class="myTextArea"></textarea>

Loop through class elements-

let o = document.getElementsByClassName("myTextArea");
for(var ele in o){
    o[ele].style.height = (o.scrollHeight - 10)+"px";
}

Fiddle -- https://jsfiddle.net/cr5ss9L0/

Upvotes: 0

abhishekkannojia
abhishekkannojia

Reputation: 2856

You can use a class and then a for loop to iterate through all the elements:

var elements = document.querySelectorAll('.txtarea'); // Assuming class txtarea
elements.forEach(function(elem) {
    elem.style.height = (elem.scrollHeight - 10) + 'px';
});

Upvotes: 1

Related Questions