Qual o erro do script? :s
Boa noite pessoal, sou novo na área de java script e estou querendo fazer um script que pegue o valor "Hello World." da tag <div> pela sua class="example" e alerte Hello World, mas quando executo o código recebo [Object HTMLCollection] como resposta, onde está meu erro?
<!DOCTYPE html> <html> <body> <div class="example">Hello World.</div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = document.getElementsByClassName("example"); window.alert(x); } </script> </body> </html>
Foxtery
Curtidas 0
Respostas
Raylan Zibel
15/04/2016
<!DOCTYPE html> <html> <body> <div class="example" id="example">Hello World.</div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { //var x = document.getElementsByClassName("example"); var x = document.getElementById("example"); window.alert(x.innerText); } </script> </body> </html>
Precisa ser pelo nome da classe?
GOSTEI 0
Foxtery
15/04/2016
Vaaleu, funcionou, mas está obtendo pela id, seria possível obter pela class?
GOSTEI 0
Raylan Zibel
15/04/2016
Implemente jQuery, vai ficar bem mais fácil. Com jQuery fica fácil referenciar pelas classes.
GOSTEI 0
Foxtery
15/04/2016
Onde estou errando?
<!DOCTYPE html> <html> <head> <title></title> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <div class="example">Hello World.</div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = $( ".example" ); window.alert(x.innerText); } </script> </body> </html>
GOSTEI 0
Raylan Zibel
15/04/2016
<!DOCTYPE html> <html> <head> <title></title> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <div class="example">Hello World.</div> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = $( ".example" ); window.alert(x.html()); // aqui } </script> </body> </html>
GOSTEI 0
Foxtery
15/04/2016
Obrigado Raylan, você é fera mesmo!
GOSTEI 0