JavaScript code

2

I'm still struggling in the area of Ti, someone could help me with the following code, it would be simple but extremely important thing in my course work, follow the Html code

<html>
<head>
<title>Projeto</title>
<style>
  body {text-align: center; }
  .retangulo {margin: auto; border: 2px solid black;}

  #ret0 {width: 400px;background-color: gray;}

  #ret1 {background-color: red;}
  #ret2 {background-color: yellow;}
  #ret3 {background-color: green;}

  #ret0 div {
margin: 20px auto;
width: 64px;
height: 64px;
  }

</style>
<script type="text/javascript" src="java.js"></script>
</head>
<body>

<div id="ret0" class="retangulo">
<div id="ret1" class="retangulo"></div>
<div id="ret2" class="retangulo"></div>
<div id="ret3" class="retangulo"></div>
<p id="texto">O que o JavaScript Pode fazer.</p>
<input type="button" onclick="acao()"value="Ação"/>
</div>
<p><em>Maxwell Gomes de Arruda</em></p>
</body>
</html>

In this case this is my index.html code. What I wanted was that in the java.js file - clicking on each colored square (individually) would appear a "text" and when clicking the action button, delete the text inserted in the colored squares.

    
asked by anonymous 23.08.2017 / 20:31

1 answer

1

Here is an example of how you can do this JavaScript:

var divs = document.querySelectorAll('.texto')

for(var i=0; i<divs.length; i++) {
  divs[i].addEventListener('click', function() {
    this.innerHTML = 'TEXTO';
  });
};

function acao() {
  for(var i=0; i<divs.length; i++) {
    divs[i].innerHTML = '';
  };
}
body {text-align: center; }
  .retangulo {margin: auto; border: 2px solid black;}

  #ret0 {width: 400px;background-color: gray;}

  #ret1 {background-color: red;}
  #ret2 {background-color: yellow;}
  #ret3 {background-color: green;}

  #ret0 div {
margin: 20px auto;
width: 64px;
height: 64px;
  }
<div id="ret0" class="retangulo">
  <div id="ret1" class="retangulo texto"></div>
  <div id="ret2" class="retangulo texto"></div>
  <div id="ret3" class="retangulo texto"></div>
  <p id="texto">O que o JavaScript Pode fazer.</p>
  <input type="button" onclick="acao()"value="Ação"/>
</div>
<p><em>Maxwell Gomes de Arruda</em></p>
    
23.08.2017 / 20:48