简体   繁体   中英

Hide a table row element inside a table using javascript

I want to hide a table row when a td has no value, but my javascript function is failing. It keeps going on the "else".

HTML

<table>
   <tr id="locOfWorkRow"> 
     <td><span>Location of Work</span></td>
   </tr>
   <tr>
     <td><span>This is the label</span></td>
     <td id="road"><span></span></td>
   </tr>
</table>

Javascript

var r = document.getElementById('road').innerHTML; 

 if(r == ""){ alert("on if");
   document.getElementById('locOfWorkRow').style.display = "none";
 }else{
    alert("on else");
 }

Instead of checking for an empty string, check whether the length of the innerHTML is more than 0 instead.

r.length > 0

If the string is empty, the length will return 0, if the the innerHTML contains any characters the length will return a value greater than 0.

What you are currently doing with r == "" is checking whether r is empty and that is why the "on if" alert is showing.

See this example

http://jsfiddle.net/9ny6598u/

var r = document.getElementById('road').innerHTML;

if (r.length > 0) {
    alert("on if");
    document.getElementById('locOfWorkRow').style.display = "none";
} else {
    alert("on else");
}

DEMO

You are using wrong if condition

use if(r != "") instead of r==""

Actually your if condition is wrong

Example : http://jsfiddle.net/kevalbhatt18/bvop1gdq/

 if(r !== ""){ alert("on if"); document.getElementById('locOfWorkRow').style.display = "none"; }else{ alert("on else"); } 

Or

 if (r.length > 0) { alert("on if"); document.getElementById('locOfWorkRow').style.display = "none"; } else { alert("on else"); } 

Hope you are not loading your javascript before page try to write your javascript at the end of the page so the element is available and you not get the null reference.

and by innerhtml you got the "span Road 1 /span" so write condition as per that. and its work fine if you load your script below body.

Make sure you have loaded your script after html load.

using undefined as comparison instead of empty string and also use === instead of ==

if(r === undefined){ alert("on if");
  document.getElementById('locOfWorkRow').style.display = "none";
}else{
  alert("on else");
}

可以使用innerText或textContent代替innerHTML

var r = document.getElementById('road').innerText || document.getElementById('road').textContent; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM