SlideShare uma empresa Scribd logo
1 de 12
Baixar para ler offline
Bloco 5.2
JavaScript - Trabalhando com
Elementos
Elaborado por Ruâni Filipe (aluno - Turma 8), com base
em anotações pessoais do assunto, via Course e Aulas
ao Vivo
Objetivos:
Adicionar e remover elementos HTML,
usando o JavaScript
Buscar elementos da página, usando a
propriedade parentNode
Buscando Elementos
DOM (Document Object Model)
Para melhor entender o assunto, vale olhar
a árvore DOM e fazer relações de
parentesco, tal qual uma árvore
genealógica
Observando a imagem ao lado (igual à
imagem anterior), percebemos que:
Body seria o pai de todos os elementos de
sua linha abaixo, assim como o Header
seria o pai de relação ao seu H1, assim
como e que os <li> são filhos de <ul> e
assim por diante
Buscando Elementos
Estruturação: document.querySelector (.nomeClasse).parentNode
Significa -> qual o elemento pai do .nomeClasse?
Obs.: Vale também para (#nomeId) e (tag)
Também é possível subir as “gerações” e buscar pelo avô, bisavô…
Basta concatenar outros .parentNode
Ex.: document.querySelector (.nomeClasse).parentNode.parentNode
Atenção: A propriedade .parentNode é somente leitura, isto é, não se pode reatribuir
valores por meio dela
Buscando Elementos (.parentNode)
Estruturação: document.querySelector (.nomeClasse).childNodes
Significa -> quais são os elementos filhos? (retorna na forma de Array)
Obs.: ele retorna as linhas (que atendam à filiação) por completo
Estruturação: document.querySelector (.nomeClasse).children
Retorna apenas os elementos HTML (e não a linha por inteiro) que sejam filhos
Buscando Elementos (outras propriedades de “filiação”)
firstChild x firstElementChild
Estruturação: document.querySelector (.nomeClasse).firstChild
Significa -> qual o primeiro nó-filho?
Estruturação: document.querySelector (.nomeClasse).firstElementChild
Significa -> qual o primeiro elemento-HTML-filho?
nextSibling x nextElementSibling
Segue o mesmo raciocínio acima, .nextSibling -> traz o próximo nó; enquanto
.nextElementSibling traz o próximo elemento
Buscando Elementos (outras propriedades de “filiação”)
Criando Elementos e
Adicionando e Removendo Filhos
Estruturação: document.createElement(“h1”).innerHTML
Entre parênteses é o parâmetro da função .createElement
Vale também para (#nomeId) e (.nomeClasse)
Exemplo prático ao lado:
uma variável para melhor organizar, criando div;;
div.className é para atribuir o nome da div criada;
div.id atribui o nome ao id da div criada
estrutura criada ao final <div class…>
Criando elementos (.createElement)
Estruturação: document.nomePai.appendChild(nomeFilho)
Ex.: document.body.appendChild(div) -> para criar um filho <div> ligado direto
ao <body>
Exemplo ao lado mostra:
1) a criação do (desgarrado) elemento filho;
2) a criação do “cordão umbilical” com o body;
3) estilizações diversas
.innerHTML -> acrescentando texto;
.style.backgroundColor -> acrescentando
cor de fundo
Criando filhos (.appendChild)
Estruturação: document.nomePai.removeChild(nomeFilho)
Ex.: document.body.removeChild(div) -> para remover um filho <div> ligado
direto ao <body>
Caso queira remover mais de um filho, pode-se fazer um for… ...of
O for… ...of vai contar div por div, dentre todas as divs (nesse exemplo) e a cada
elemento div encontrado (que seja filho de <body>), ele a remove
ATENÇÃO: Usa-se o for, pois o retorno do .querySelectorAll é um Array
Removendo filhos (.removeChild)

Mais conteúdo relacionado

Último

ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx2m Assessoria
 
Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsDanilo Pinotti
 
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx2m Assessoria
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx2m Assessoria
 
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docxATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx2m Assessoria
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploDanilo Pinotti
 

Último (6)

ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docxATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
ATIVIDADE 1 - GCOM - GESTÃO DA INFORMAÇÃO - 54_2024.docx
 
Boas práticas de programação com Object Calisthenics
Boas práticas de programação com Object CalisthenicsBoas práticas de programação com Object Calisthenics
Boas práticas de programação com Object Calisthenics
 
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docxATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
ATIVIDADE 1 - LOGÍSTICA EMPRESARIAL - 52_2024.docx
 
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docxATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
ATIVIDADE 1 - CUSTOS DE PRODUÇÃO - 52_2024.docx
 
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docxATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
ATIVIDADE 1 - ESTRUTURA DE DADOS II - 52_2024.docx
 
Padrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemploPadrões de Projeto: Proxy e Command com exemplo
Padrões de Projeto: Proxy e Command com exemplo
 

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Bloco 5.2

  • 1. Bloco 5.2 JavaScript - Trabalhando com Elementos Elaborado por Ruâni Filipe (aluno - Turma 8), com base em anotações pessoais do assunto, via Course e Aulas ao Vivo
  • 2. Objetivos: Adicionar e remover elementos HTML, usando o JavaScript Buscar elementos da página, usando a propriedade parentNode
  • 5. Para melhor entender o assunto, vale olhar a árvore DOM e fazer relações de parentesco, tal qual uma árvore genealógica Observando a imagem ao lado (igual à imagem anterior), percebemos que: Body seria o pai de todos os elementos de sua linha abaixo, assim como o Header seria o pai de relação ao seu H1, assim como e que os <li> são filhos de <ul> e assim por diante Buscando Elementos
  • 6. Estruturação: document.querySelector (.nomeClasse).parentNode Significa -> qual o elemento pai do .nomeClasse? Obs.: Vale também para (#nomeId) e (tag) Também é possível subir as “gerações” e buscar pelo avô, bisavô… Basta concatenar outros .parentNode Ex.: document.querySelector (.nomeClasse).parentNode.parentNode Atenção: A propriedade .parentNode é somente leitura, isto é, não se pode reatribuir valores por meio dela Buscando Elementos (.parentNode)
  • 7. Estruturação: document.querySelector (.nomeClasse).childNodes Significa -> quais são os elementos filhos? (retorna na forma de Array) Obs.: ele retorna as linhas (que atendam à filiação) por completo Estruturação: document.querySelector (.nomeClasse).children Retorna apenas os elementos HTML (e não a linha por inteiro) que sejam filhos Buscando Elementos (outras propriedades de “filiação”)
  • 8. firstChild x firstElementChild Estruturação: document.querySelector (.nomeClasse).firstChild Significa -> qual o primeiro nó-filho? Estruturação: document.querySelector (.nomeClasse).firstElementChild Significa -> qual o primeiro elemento-HTML-filho? nextSibling x nextElementSibling Segue o mesmo raciocínio acima, .nextSibling -> traz o próximo nó; enquanto .nextElementSibling traz o próximo elemento Buscando Elementos (outras propriedades de “filiação”)
  • 9. Criando Elementos e Adicionando e Removendo Filhos
  • 10. Estruturação: document.createElement(“h1”).innerHTML Entre parênteses é o parâmetro da função .createElement Vale também para (#nomeId) e (.nomeClasse) Exemplo prático ao lado: uma variável para melhor organizar, criando div;; div.className é para atribuir o nome da div criada; div.id atribui o nome ao id da div criada estrutura criada ao final <div class…> Criando elementos (.createElement)
  • 11. Estruturação: document.nomePai.appendChild(nomeFilho) Ex.: document.body.appendChild(div) -> para criar um filho <div> ligado direto ao <body> Exemplo ao lado mostra: 1) a criação do (desgarrado) elemento filho; 2) a criação do “cordão umbilical” com o body; 3) estilizações diversas .innerHTML -> acrescentando texto; .style.backgroundColor -> acrescentando cor de fundo Criando filhos (.appendChild)
  • 12. Estruturação: document.nomePai.removeChild(nomeFilho) Ex.: document.body.removeChild(div) -> para remover um filho <div> ligado direto ao <body> Caso queira remover mais de um filho, pode-se fazer um for… ...of O for… ...of vai contar div por div, dentre todas as divs (nesse exemplo) e a cada elemento div encontrado (que seja filho de <body>), ele a remove ATENÇÃO: Usa-se o for, pois o retorno do .querySelectorAll é um Array Removendo filhos (.removeChild)