Search code examples
javascripthtmlgoogle-chrome-devtoolshtml-parsinginnerhtml

Console (F12) correcting "broken" HTML (innerHTML)


I was checking my code and noticed something I hadn't realized before. The Console was not showing my code but displaying "corrected" data. I suppose it makes sense that it would show what Chrome displays but I did waste a lot of time as I could not find the error in my code.

The question is: how do people deal with this issue?

Is there a way to have the "fixed" code displayed in red (for example)?

Or to turn it off?


Example:

    for ( i=0; i<usStates.length; i++){

          addToUSstates.innerHTML=addToUSstates.innerHTML+"<option>"+usStates[i][0]+"";
}

displays <option> State Name </option>

instead of <option> State Name (which it would if the browser didn't "correct" the code.)


And, that being so - why are <td>snot rendered.

Example:

for ( i=0; i<10; i++){

      addToExcel.innerHTML=addToExcel.innerHTML + "<td>aaa</td>";
}

displays aaaaaaaaa (without the <td> and </td>) whereas

for ( i=0; i<10; i++){

      addToExcel.innerHTML=addToExcel.innerHTML + "<div>aaa</div>";
}

displays things correctly: <div> aaa </div>


EDIT: The full code for the table:

    for ( i=0; i<10; i++){

addToExcel.innerHTML=addToExcel.innerHTML + "<tr><td>aaa</td></tr>";

}

addToExcel.innerHTML="<table>"+addtoExcel.innerHTML;
addToExcel.innerHTML=addtoExcel.innerHTML+"</table>";

Solution

  • Because that’s how innerHTML works.

    The behavior you’ll get from your code examples is not specific to anything that browser devtools do. When you set innerHTML—regardless of where you set it—the browser first parses what you assign to it. It’s not putting strings into the DOM. So what you are seeing is the serialization from the DOM result of parsing those input strings-containing-HTML that you’re starting from.

    Is there a way to have the "fixed" code displayed in red (for example)?

    No, there is not. Not unless you want to first manually store a copy of each input string in some variable in your code, and compare it later to what comes back from getting .innerHTML. Otherwise, browsers don’t keep a record around of every string you’ve given them, and every operation they’ve performed on it so that you can roll it back or whatever.

    Or to turn it off?

    No, you can’t turn it off. If you’re using DOM operations, you’re asking for HTML parsing. Browsers do HTML parsing in a standard way, following common rules that are in the HTML spec. You don’t get to choose your own rules or specify custom ones or whatever.