matt
matt

Reputation: 44413

bookmarklet: inserting text into textarea with js?

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: 3649

Answers (4)

Ilian Iliev
Ilian Iliev

Reputation: 3236

In jQuery, you have to use it this way:

For a single element, then use $('#element_id').html('your HTML here'). Use $('textarea').val('your HTML here') for changing all text areas.

I have to confess that I'm not sure why it works this way, but it does. Use frameworks; they will save you time and nerves.

Upvotes: 0

robinst
robinst

Reputation: 31477

In case anyone wonders how to use the currently focused text field, use the following:

document.activeElement.value = "...";

Upvotes: 1

instanceof me
instanceof me

Reputation: 39208

Unlinke getElementById, getElementsByTagName has an sat 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

Tim Down
Tim Down

Reputation: 324727

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

Related Questions