-4

Need to get the value 40.78 from <span> to be stored in <span id ="test">.

Tried the code below. But not able to figure out what's going wrong. The error getting on console is :

Uncaught ReferenceError: div is not defined.

Any help would be really appreciated.

var span = div.getElementsByTagName("span");
var test = document.getElementById('test');
console.log(test.innerHTML = span.innerHTML);
<span>40.78</span>
<span id="test"></span>
mhodges
  • 10,938
  • 2
  • 28
  • 46

2 Answers2

1

div is not defined any where in the code. Use document instead.

getElementsByTagName() returns collection, you have to use index. I will also suggest you to use textContent instead of innerHTML when dealing with text only content:

<html>
  <body>
   <div>
    <span>40.78</span>
   </div>
    <span id = "test"></span>
     <script>
      var span = document.getElementsByTagName("span")[0];
      var test = document.getElementById( 'test' );
      test.textContent = span.textContent;
      console.log(test.textContent);
     </script>
 </body>
</html>
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

The error says it is not defined, and you don't define it anywhere.

If you want to use it, you need to define it.

e.g.

var div = document.querySelector('div');

Re edit.

The solution in the above answer doesn't apply to the edited code. It is no longer clear what you expect the div variable (which is still undeclared) to represent.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335