Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript length property (basic)

Tags:

javascript

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>
like image 408
Flower Avatar asked Jul 12 '26 19:07

Flower


2 Answers

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>
like image 155
saurabh Avatar answered Jul 15 '26 09:07

saurabh


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.

like image 34
Yngvarr Avatar answered Jul 15 '26 07:07

Yngvarr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!