<!DOCTYPE html>
<html>
<body>
<h5>Copy-Text-from-textarea-to-div.html</h5>
Field1: <input type="text" id="field1" value="Hello from Field1 !"><br>
Field2: <input type="text" id="field2"><br><br>
<button onclick="myFunction()">Copy text From field1 to field2</button>
<button onclick="saveItAll()">Copy text From textarea to contentEditable-div</button>
<br><br>
<textarea rows="4" cols="20" class="copyFrom" >TextArea1 </textarea>
<br>
<textarea rows="4" cols="20" class="copyFrom" >TextArea2 </textarea>
<br>
<div class="pastInto" contentEditable="true" >pastInto 1</div>
<div class="pastInto" contentEditable="true" >pastInto 2</div>
<p>A function is triggered when the button is clicked. The function copies the text from Field1 into Field2.</p>
<script>
var copyFromVar; var pasteIntoVar;
var fromCount; // = document.getElementsByClassName("copyFrom");
var intoCount; // = document.getElementsByClassName("pasteInto");
function saveItAll() {
copyFromVar = document.getElementByClassName("copyFrom"[0]).value;
document.getElementByClassName("pastInto"[0]).innerHtml = "copyFromVar"
copyFromVar = document.getElementByClassName("copyFrom"[1]).value;
document.getElementByClassName("pastInto"[1]).innerHtml = "copyFromVar"
}
</script>
<script>
function myFunction() {
document.getElementById("field2").value = document.getElementById("field1").value;
}
</script>
</body>
</html>
The getElementByClassName function takes a class value as its argument:
<p class="bar">Hello!</p>
To access this element, you would use document.getElementByClassName("bar"). I am not quite sure what you are trying to do here, but you can’t use the array syntax or anything non-class related inside the getElementByClassName function. Also, this function only returns one single element. If you want to access all elements by a class value and then target a particular element, you can use getElementsByClassName (note the plural form of elements) and then use the index position of the element you wish to access:
var secondElement = document.getElementsByClassName("foo")[1];
If you want to use something more modern, you should look into querySelector and querySelectorAll. They are more flexible in the elements you can target beyond just class or id This will help: Finding Elements in the DOM using querySelector
When you run into something that doesn’t work, always check your Console to see if any errors are raised. In your case, copying into the div shows this:
In your code, you never declared a variable called pasteInto. My guess is that you want that variable to store the results of a getElementsByClassName, but I’ll leave it to you to investigate further given these pointers
Some hints: The way to get the value of an input element or textarea is not through innerHTML, but through value. Also, there is no valid property called innerHtml. It should be innerHTML