# Auto Resize a `<textarea>` with an `autosize` Attribute

First, a regular `<textarea>`.

<textarea>Will NOT auto resize.</textarea>

Now add an attribute to tell the element to automatically resize on input, i.e. `<textarea autosize>`.

<textarea autosize>Will auto resize.</textarea>

What about `<textarea>`s that get injected into the DOM after page load with the `autosize` attribute? A mutation observer can pick up on those and attach the appropriate events. This ensures any `<textarea autosize>` added to the DOM via JavaScript will resize as expected.

All other attributes on the `<textarea>` continue to work as normal.
View Compiled
textarea {
  display: block;
  margin: 20px 0;
  width: 400px;
import autosize from 'https://cdn.skypack.dev/[email protected]';

// Autosize anything in the DOM on page load

// Setup observer to autosize anything after page load
new MutationObserver(mutations => {
  Array.from(mutations).forEach(mutation => {
    Array.from(mutation.addedNodes).forEach(node => {
      if (node.matches("textarea[autosize]")) {
}).observe(document.body, { childList: true });

// Simulate injecting new <textarea> nodes
setTimeout(() => {
  const t1 = document.createElement("textarea");
  t1.setAttribute("autosize", true);
  t1.innerHTML = "Injected after page load. Will auto resize."
  const t2 = document.createElement("textarea");
  t2.innerHTML = "Injected after page load. Will NOT auto resize."
}, 1000)
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.