I have tried, as many have suggested, saving a variable as the .value or .innerHTML of an ID, found by using document.getElementById. Here is all of my HTML:
<html>
<head>
<title>write</title>
<script type="text/javascript" src="g.js"></script>
<link rel="stylesheet" type="text/css" href="g.css" />
</head>
<body>
<div id="box">
<textarea id="txt" placeholder="placeholder. type here.">text text</textarea>
</div>
</body>
</html>
and here is my javascript, currently meant to fire an alert that contains the text in the text area – right now that would be, text text:
function run(){
var txt = document.getElementById('txt');
alert(txt);}
run()
Right now, loading the page fires an alert with the text Null and adding .value after getElementById('txt') results in no alert. Many thanks in advance.
The problem is that your javascript is executing before the DOM is constructed. When you load the JavaScript file in the
<head>of the document, it is executed immediately, before the<textarea>tag has been created.Try moving your script block below the textarea, just before the
</body>tag.Here’s an example: fiddle
After the DOM is constructed you can use
getElementByIdjust as have and can access the contents of the textarea with thevalueattribute. All of this is in the fiddle above.Alternatively, you can wrap your
run()method call with a library that provides an event when the DOM becomes ready. jQuery’s example would be: