Skip to content
Advertisement

ScalaJS document.getElementById(“editor”).getAttribute(“value”) always returns null

I am trying to access the value of a textarea in scalajs like so:

document.getElementById("editor").addEventListener("input", { (e: dom.Event) =>
      console.log(e)
      console.log(document.getElementById("editor").getAttribute("value"))
    })

But it always returns null. Not sure why!

I tried the same thing in plain vanilla javascript and that seems to work just fine!

<script>
     document.getElementById("editor").addEventListener("input", function(){
        console.log(document.getElementById("editor").value);
     });
</script>

I am using scalajs version 1.3.1.

Any help is appreciated. TIA.

Advertisement

Answer

Apparently we have to cast the results of document.getElementById to org.scalajs.dom.html elements.

In this case, before we can even add event listeners to the editor component, we need to first cast the result of document.getElementById("editor") to org.scalajs.dom.html.TextArea, like so:

val editor = document.getElementById("editor").asInstanceOf[TextArea]

then if we wish to access the value attribute of this component, we could do it like so:

editor.addEventListener("input", { (e: dom.Event) =>
    console.log(editor.value)
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement