Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is .trim() valid for innerText?

Tags:

javascript

This is failing. Is my use of trim valid? The span is inside a table row.

 var x = document.getElementById('myRow');
 var r = x.getElementsByTagName('span')[1].innerText;

 if(r.trim() == ""){
   alert("on if")
 }

HTML

<tr id="header"> 
   <td><span>The Header</span></td>
</tr>
<tr id="myRow">
 <td><span>Sample</span></td>
 <td><span></span></td>
</tr> 
like image 988
Ti J Avatar asked Dec 06 '25 02:12

Ti J


1 Answers

You're code works if coupled with the correct html

Sample HTMl:

<table>
    <tr id="header"> 
       <td><span>The Header</span></td>
    </tr>
    <tr id="myRow">
        <td><span>Sample</span></td>
        <td><span></span></td>
    </tr> 
</table>

JSFiddle:

https://jsfiddle.net/vfhogegd/4/

Note

Arrays start at index 0

Did you mean to refer to the first span? if so you need to use [0] instead of [1]

UPDATE

Based on your HTML, the issue is that you don't have <table> tags...

If you look at your console you will probably see the following error:

Uncaught TypeError: Cannot read property 'getElementsByTagName' of null

If you do not have <table> tags around your <td> tags, it is invalid html, most browser will ignore your tags which is why your getElementByID isn't returning anything causing the rest of your function to fail

like image 68
Seth McClaine Avatar answered Dec 08 '25 16:12

Seth McClaine



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!