Javascript - Content of a TD comparing to a variable

Asked

Viewed 76 times

1

I am making a script that clears the following 3 elements.
In If the clause has to fall into the true one (I made the query through the console.log and have to fall into the true one, but 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>

  • 1

    (Tds1[i]. innerHTML === Tds1) will never be true, you are comparing the current td with the object that stores all tds, what you really want to do in this part?

  • Sorry @Felipe, the comparison should compare the td element with the idAntiga, still even falls in the If, corrected the question there, pardon again

  • 1

    Ata understood your problem

1 answer

2


Note that the elements in td are spaced, the innerHTML take this spacing, and when checking it will interfere, an alternative is the innerText that takes only 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>

  • 1

    Ah, got it !! Thanks for the explanation and help @Felipe !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.