What I am doing wrong?
javascript:document.getElementsByTagName('textarea').innerHTML='inserted';
I want to create a bookmarklet to insert simple text to a textarea on a given webpage.
What I am doing wrong?
javascript:document.getElementsByTagName('textarea').innerHTML='inserted';
I want to create a bookmarklet to insert simple text to a textarea on a given webpage.
Share Improve this question edited Nov 26, 2020 at 19:16 peterh 1 asked Oct 1, 2010 at 6:59 mattmatt 44.4k107 gold badges268 silver badges402 bronze badges4 Answers
Reset to default 6Use the value
property rather than innerHTML
and make sure your code evaluates to undefined
, which you can do by wrapping it in a function with no return
statement. If you don't do this, the contents of the page will be replaced with whatever your code evaluates to (in this case, the string 'inserted').
javascript:(function() {document.getElementsByTagName('textarea')[0].value = 'inserted';})();
Update 14 January 2012
I failed to spot the fact that the original code was treating document.getElementsByTagName('textarea')
as a single element rather than the NodeList
it is, so I've updated my code with [0]
. @streetpc's answer explains this in more detail.
Unlinke getElementById
, getElementsByTagName
has an s
at Elements
because it returns an array array-like NodeList of the matching elements. So you'll have to access one of the elements first, let's say the first one for simplicity:
javascript:void((function(){document.getElementsByTagName('textarea')[0].value='inserted'})())
Also, as mentioned by others, value
property rather than innerHTML
here.
In case anyone wonders how to use the currently focused text field, use the following:
document.activeElement.value = "...";
In jQuery you have to use if this way:
for single element -> $('#element_id').html('your html here')
for all text areas -> $('textarea').val('your html here')
I have to confess that I`m not sure why it works this way but it works. And use rameworks, they will save you time and nerves.