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

142
Visualizações
the DOM doesn't work with me when I try to sort an element

here is the file I have. when I try to sort some number it doesn't change and keeps empty

HTML file

<tr>
<th>Original array</th>
<td id ="td1">1,5,7,-1,3</td></tr>
<tr>
<th>Sorted Array</th>
<td id="td2"></td>

JS file

var OriginalArr = document.getElementById("td1").value;
var a =  document.getElementById("td2").value;
a.value = Original.sort();
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are two main problems with this. First of all, most elements do not have a value property, only the elements that take input. You seem to be looking for textContent in this context.

Another thing is that when you get the text in td1 it must be converted to an array before you can sort it.

Here is the code with the mentioned problems fixed:

// Get text in td1
var td1Text = document.getElementById("td1").textContent;

// Get array of numbers from text
var OriginalArray = td1Text.split(",").map(function(num){
  return parseInt(num,10);
});

// Get td2
var td2 =  document.getElementById("td2");

// Set td2 to sorted array converted to string
td2.textContent = OriginalArray.sort().toString();
<table>
<tr>
<th>Original array</th>
<td id ="td1">1,5,7,-1,3</td></tr>
<tr>
<th>Sorted Array</th>
<td id="td2"></td></tr>
</table>

One more thing to note is that the <tr> tags must be in a <table> in order to be properly queried by getElementById. Without the table tag, getElementById returns null.

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