Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a value of the textarea without id by javascript?

Typically we run javascript code to set any value:

document.getElementById('id_name').value = "...";

But I have a page like this:

<div id="id_name">
    <div class="class_name">
        <textarea></textarea>
    </div>
</div>

How to set a value of the textarea by javascript?

Thanks a lot for help!

like image 980
Dmitry Avatar asked Dec 04 '11 15:12

Dmitry


3 Answers

You could do this, if your HTML is really that simple:

var textarea = document.getElementById('id_name').getElementsByTagName('textarea')[0];
textarea.value = "hello world";

There's also a "getElementsByClassName()" in newer browsers that could be used to find the "class_name" <div> element, from which you'd do the "getElementsByTagName()" call.

like image 150
Pointy Avatar answered Nov 14 '22 21:11

Pointy


Modern browsers support the Selectors API (through querySelector), which lets you do this very easily:

document.querySelector("#id_name > .classname > textarea").value = "foo";

For completeness, I should mention that this will operate on the first element that matches the selector (you can also tweak the selector of course). If there is the possibility of having many elements that need to be targeted, you can switch to querySelectorAll and a loop.

like image 36
Jon Avatar answered Nov 14 '22 21:11

Jon


There are a few differerent possibilities and many context:

document.querySelector("textarea").value = "Your text";// Set a first textarea find in a page.

document.querySelectorAll("textarea").value = "Your text";// Set all textarea find in a page.

document.getElementById('myForm').querySelector("textarea").value = "Your text";// Set a textarea into a form: (frequently used).
like image 43
Josias Wattrelos Avatar answered Nov 14 '22 22:11

Josias Wattrelos