aquinas
aquinas

Reputation: 23786

Cannot get outerHTML/value of a dynamically added textarea

This fiddle https://jsfiddle.net/xa9m49zy/ demonstrates that you can get the outerHTML (with the text area value) of a textarea that is in the DOM when it renders, but when the textarea is dynamically added to the DOM, the outerHTML doesn't contain the text area value. It doesn't work in Firefox and Chrome but it does work in IE and Edge.

HTML:

<textarea id="abc">
  Test
</textarea>

JS:

console.log($("#abc").get(0).outerHTML); //returns everything as expected
$("<textarea id='xyz'></textarea>").val("Test 2").appendTo("body");
console.log($("#xyz").get(0).outerHTML); //only shows <textarea></textarea> in non-MS browsers

What is going on here? Is this a bug in Chrome and Firefox?

Upvotes: 1

Views: 1297

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65808

The problem is that you are setting the value of the second textarea using .val(), but outerHTML does not retrieve values, it retrieves an element and the content of that element.

textarea elements get their value from their content.

If you set the content for the second textarea using the .text() method, it works.

alert($("#abc").get(0).outerHTML); //returns everything as expected
$("<textarea id='xyz'></textarea>").text("Test 2").appendTo("body");
alert($("#xyz").get(0).outerHTML); //only shows <textarea></textarea> in non-MS browser
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<textarea id="abc">
  Test
</textarea>

Upvotes: 3

Related Questions