I apply ".length" on the element has id="name", but it counts 29 instead of 14. I wonder where is my mistake? It would be nice if someone can let me know. Thank you!
var name=document.getElementById('name');
var totalTiles=document.getElementById('totalTiles');
totalTiles.textContent=name.length;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="heading"></div>
<table>
<tr>
<th>Custom sign:</th>
<td id='name'>Montague House
</td>
</tr>
<tr>
<th>Total tiles:</th>
<td id='totalTiles'></td>
</tr>
</table>
<button>Pay Now</button>
<script src="script.js"></script>
</body>
</html>
This is happening because the name variable is the entire dom element (td).
Try using innerText to get the required value
var name = document.getElementById('name').innerText;
var totalTiles = document.getElementById('totalTiles');
totalTiles.textContent = name.length;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="heading"></div>
<table>
<tr>
<th>Custom sign:</th>
<td id='name'>Montague House
</td>
</tr>
<tr>
<th>Total tiles:</th>
<td id='totalTiles'></td>
</tr>
</table>
<button>Pay Now</button>
<script src="script.js"></script>
</body>
</html>
Because the name variable returns [object HTMLTableCellElement] and not the string you intended to return. The length of the [object HTMLTableCellElement] is 29 so that's what the length property returns.
To get the value of the actual string you need to count the length of the variable after applying the .innerText property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With