If statement in HTML using JS

I am new to JS and I am displaying results using javascript document.getElementById(bj).innerHTML = Result in the HTML part I created table to display the result

<table>
            <tr>
                <th>subject1</th>
                <th>marks</th>
            </tr>
            <tr>
                <td>mathematics</td>
                <td><p id="maths"> </p></td>
                
            </tr>

            <tr>
                <td>science</td>
                <td><p id="science"> </p></td>
            </tr>
</table>

Here I want to display the row if that id (<p id="maths"> </p>) has present any value otherwise it should hide the entire row

Thanks

Answer

Kammar,

Since you mention that you are using document.getElementById(bj).innerHTML = Result for some part of your content, I will provide a “templating based” solution which works in a similar way. Note that this solution will require regenerating HTML if different “marks” changes value or become null.

The following HTML and javascript code will achieve your goals and has been tested in codepen.io. Make sure the javascript is run after the HTML is loaded. This can be done by just putting the javascript code in a <script> tag after the HTML portion

HTML Code:

<table>
    <thead>
        <tr>
            <th>subject1</th>
            <th>marks</th>
        </tr>
    </thead>
    <tbody id="tableBody">
    </tbody>

</table>

javascript code:

var marks={"mathematics":null,"science":89,"history":92} //some example data
var generatedHTML = ""
var rowTemplate=`
        <tr>
            <td>{{subject}}</td>
            <td><p id="{{subject}}">{{mark}}</p></td>
        </tr>
    `
var tableBody=document.getElementById("tableBody")
for(var key in marks){
   if(marks.hasOwnProperty(key)){
       var subject = key;
       if (marks[subject])
       {
           var rowHTML=rowTemplate.replace(/{{subject}}/g,subject).replace(/{{mark}}/g,marks[subject]);
           generatedHTML+=rowHTML
       }
   }
}
tableBody.innerHTML=generatedHTML

I hope you can learn some things from the code.

If you want a very generalized and powerful solution to these types of problems, I advise learning React.js. React.js allows for conditional rendering (which is the nature of your problem), as well as handling DOM events and a host of other things.

Thanks, Mike