JavaScript - Content of a TD comparing with a variable

1

I am making a script that cleans the following 3 elements. Home In If the clause has to fall into the true (I made the query through console.log and have to fall into the true one, however it falls into the false position.) Can you help me figure out why ??

	function teste(){
	    var idAntigo = "123"
        var tds = document.querySelectorAll("#tblItens td");
        var values = [];
        var tabela = document.querySelector("#tblItens");
        var TDs1 = tabela.getElementsByTagName("td");
        console.log("Caiu aqui");
        for (i = 0; i < TDs1.length; i++) {
        console.log("Aqui também");
            if (TDs1[i].innerHTML === idAntigo ) {
        console.log("Aqui não");
                TDs1[i].innerHTML = "";
                TDs1[i + 1].innerHTML = "";
                TDs1[i + 2].innerHTML = "";
                TDs1[i + 3].innerHTML = "";
                break;
            } else { console.log("false")}
        }
    } 
<html>
<body>
	<table id="tblItens">
		<tr>
			<td> 123 </td>
			<td> 124 </td>
			<td> 123 </td>
		</tr>
			<td> 123 </td>
		<tr>
			<td> 125 </td>
			<td> 124 </td>
		</tr>
	</table>
	<button onclick="teste()"> teste </button>
  </body>
</html>
    
asked by anonymous 30.11.2017 / 13:50

1 answer

2

Note that the elements in td are spaced, innerHTML takes that spacing, and when checking this will interfere, an alternative is innerText that only takes the text area, example ...

function teste(){
	    var idAntigo = "123"
        var tds = document.querySelectorAll("#tblItens td");
        var values = [];
        var tabela = document.querySelector("#tblItens");
        var TDs1 = tabela.getElementsByTagName("td");
        for (i = 0; i < TDs1.length; i++) {
            if (TDs1[i].innerText == idAntigo ) {
            console.log("agora caiu");
                TDs1[i].innerHTML = "";
                TDs1[i + 1].innerHTML = "";
                TDs1[i + 2].innerHTML = "";
                TDs1[i + 3].innerHTML = "";
                break;
            } else { console.log("false")}
        }
    } 
<table id="tblItens">
		<tr>
			<td> 123 </td>
			<td> 124 </td>
			<td> 123 </td>
		</tr>
			<td> 123 </td>
		<tr>
			<td> 125 </td>
			<td> 124 </td>
		</tr>
	</table>
	<button onclick="teste()"> teste </button>
    
30.11.2017 / 14:15