Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
Why do innerHTML and textContent give different results?

I know that these 2 properties work differently. According to the spec, innerHTML works with html-tags, while textContent works with text. But I don't get why they work like that here.

//textContent
function func1() {
    let a3 = [[1, 2, 3], [3, 4, 5], [6, [7, 'my']]];
    document.querySelector('.out-1').textContent = a3[2][0][1];
}
document.querySelector('.b-1').onclick = func1;

//innerHTML
function func2() {
    let a3 = [[1, 2, 3], [3, 4, 5], [6, [7, 'my']]];
    document.querySelector('.out-2').innerHTML = a3[2][0][1];
    return a3[2][1][1];
}
document.querySelector('.b-2').onclick = func2;
.wrapper {
  margin-bottom: 50px;
}
 <!-- textContent -->
 <div class='wrapper'>
   <div>textContent</div>
   <button class="b-1">PUSH</button>
   <div class="out-1"></div>
 </div>
 
 <!-- innerHTML -->
<div class='wrapper'>
   <div>innerHTML</div>
   <button class="b-2">PUSH</button>
   <div class="out-2"></div>
</div>
 

I'll try to pull up non-existent element. textContent pulls up nothing, while innerHTML pulls up undefined. Why is that so?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Problem -

  • a3[2][0][1]; returns undefined, because there's no such element. innerHTML shows undefined but textContent treats undefined as an empty string

const o = document.getElementById('1');
const s = document.getElementById('2');

o.textContent = undefined;
s.innerHTML = undefined;

console.log(typeof o.textContent);
// this means undefined is treated as an empty string
<div id="1"></div>
<div id="2"></div>

Note:

From what i tested, innerHTML accepts anything from Objects, arrays, strings, numbers, booleans, undefined so on and it'll display [object Object], [Array] etc. except for null in that case innerHTML will resolve it to an empty content and will display nothing

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda