vusan vusan - 1 month ago 8
Javascript Question

td without parent table tag

HTML:

<td class="tabletd"> text one </td><br>
<td class="tabletd" id="tdSecond"> this is next td</td>
<button onclick="myFunc()">click</button>


JS:

function myFunc() {
var second = document.getElementById('tdSecond').innerHTML;
//var second2 = document.getElementsByTagName('td')[1]; //gives error undefined
alert(second);
}


I cannot make this work. Even there is no effect of css see JSFiddle.

But both javascript and css work fine if we use
<li>
without its parent
<ul>
.

And also javascript and css work fine on custom tag. for eg:-
<ddd> text </ddd>


So why we get error on both css and javascript if we use
<td>
without its parent
<table>
?

Answer

If you inspect the element in chrome you will notice the code has changed to the following:

<body>
    text one <br>
    this is next td
    <button onClick="myFunc()">click</button>
    <script type="text/javascript">//<![CDATA[ 

    function myFunc() {
    var second=document.getElementById('tdSecond').innerHTML;
    alert(second);

    //var second2=document.getElementsByTagName('td')[1].innerHTML;
    //alert(second2);  
    }

    //]]>  

    </script>
</body>

The td elements have been stripped by the browser as they are not valid.

Comments