Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

returning [object HTMLDivElement] when using document.getElementById

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading