0

I'm trying to change the innerHTML of each div. I'm not seeing the code work as intended. Can anybody help me understand why the changes are not occurring?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <div style="background: #FFEE05">f</div>
    <div style="background:#2B9423 ">d</div>
    <div style="background: #0024FF">s</div>
    <div style="background: #EF2E31">e</div>
    <script>
 var dvs=document.getElementsByTagName("div")
 dvs.innerHTML="<a href='#'>click here</a>"
    </script>
</body>
</html>
rustyshackleford
  • 692
  • 1
  • 7
  • 22
hossein
  • 45
  • 5
  • 2
    `getElementsByTagName` returns a collection of dom objects. Every div on the page. You can't set the HTML of all of them like that. – SpeedOfRound Apr 07 '20 at 18:31

2 Answers2

3

getElementsByTagName returns an array

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <div style="background: #FFEE05">f</div>
    <div style="background:#2B9423 ">d</div>
    <div style="background: #0024FF">s</div>
    <div style="background: #EF2E31">e</div>
    <script>
 var dvs=document.getElementsByTagName("div")
 
 for(let i=0;i<dvs.length;i++){
 dvs[i].innerHTML="<a href='#'>click here</a>"
 }
    </script>
</body>
</html>
DCR
  • 14,737
  • 12
  • 52
  • 115
2

getElementsByTagName return an array of selected items, you need to iterate over it to assign value to individual element.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

    <div style="background: #FFEE05">f</div>
    <div style="background:#2B9423 ">d</div>
    <div style="background: #0024FF">s</div>
    <div style="background: #EF2E31">e</div>
    <script>
 var dvs=document.getElementsByTagName("div")
 for (let i = 0; i < dvs.length; i++) {
   dvs[i].innerHTML="<a href='#'>click here</a>"
 }
    </script>
</body>
</html>
Jasdeep Singh
  • 7,901
  • 1
  • 11
  • 28