Reputation: 44293
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.
Upvotes: 3
Views: 3633
Reputation: 31407
In case anyone wonders how to use the currently focused text field, use the following:
document.activeElement.value = "...";
Upvotes: 1
Reputation: 39138
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.
Upvotes: 3
Reputation: 324497
Use 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.
Upvotes: 6
Reputation: 3236
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.
Upvotes: 0