I am inserting this into my html div:
<script>
document.getElementById("mArray").appendChild = '<%= mArray %>'
console.log('<%= mArray %>')
</script>
<div id="mArray"></div>
then, inside my js file, I have this:
var mArray = document.getElementById("mArray")
console.log("33: " mArray)
but when I log it, I get this:
33: [object HTMLDivElement]
i want it to return the array data, which should look like [1,3,5,7,9]
what am i doing wrong?
CodePudding user response:
When reading, use
var mArray = document.getElementById("mArray").textContent
and if you want to use it as a JS array (assuming it is a valid js array format), you could do
var mArrayContents = document.getElementById("mArray").textContent;
var myArray = JSON.parse( mArrayContents );
Additionally, when setting the value you do not have to use JS.
You can do it directly
<div id="mArray"><%= mArray %></div>
CodePudding user response:
Right now you are logging the element itself, you need to check for the data inside. Depending on how the information is stored you could possibly get the information with something such as
document.getElementById("mArray").innerHTML;
or
document.getElementById("mArray").value;