Created
September 18, 2015 12:10
-
-
Save lipelopeslage/5a403600cd692b5180b6 to your computer and use it in GitHub Desktop.
Tabela + querySelectors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head></head> | |
<body> | |
<script> | |
// CRIAR UMA TABELA E ADICIONAR NO DOM | |
// criar tabela com o conteúdo de uma lista | |
var alunos = [{nome:'Deni', ra:'1420088-1'}, | |
{nome:'Dinora', ra:'1420089-1'}, | |
{nome:'Wagner', ra:'1120108-3'}, | |
{nome:'Marco', ra:'1420101-1'}]; | |
// iniciamos a estrutura fixa da tabela | |
var tabela = '<thead><tr><th>Nomes</th>'; | |
tabela += '<th>RA</th></tr></thead><tbody>'; | |
// criamos um <tr> pra cada registro novo implementado na tabela | |
for(var i = 0, total = alunos.length; i < total; i++){ | |
tabela += '<tr><td class="aluno">'+alunos[i].nome+'</td>'; | |
tabela += '<td class="ra" name="ra">'+alunos[i].ra+'</td></tr>'; | |
} | |
//fechamos o corpo da tabela | |
tabela += '</tbody>'; | |
//document.write(tabela); // MOSTRA NA TELA | |
// VIRTUALMENTE NÃO HÁ DIFERENÇA ENTRE USAR DOCUMENT.WRITE | |
// E APPENDCHILD, A NÃO SER O CONTROLE DO LOCAL ONDE SERÁ INSERIDO | |
// criar uma tabea no documento | |
var tabelaDOM = document.createElement("table"); | |
// o conteúdo dessa tabela será a criada acima, sem as tags <table>, </table> | |
tabelaDOM.innerHTML = tabela; | |
// adiciona ao documento/render tree | |
document.body.appendChild(tabelaDOM); | |
// aplicar borda na tabela | |
tabelaDOM.setAttribute("border","1"); | |
// deixar as celulas dos alunos com fundo azul | |
var listaAlunos = tabelaDOM.querySelectorAll(".aluno"); | |
var i = 0; | |
while(i < listaAlunos.length){ | |
listaAlunos[i].style.backgroundColor = "blue"; | |
i++; | |
} | |
// deixar as celulas dos RAs com fundo amarelo | |
i = 0; // zera contador, para reutilização | |
var listaRAs = tabelaDOM.querySelectorAll("td[name=ra]"); // seletor de atributo | |
// veja na String da tabela: | |
// name="ra" | |
while(i < listaRAs.length){ | |
listaRAs[i].style.backgroundColor = "yellow"; | |
i++; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment