How to html if statement

Issue

I want to display a button only if a statement is true:

 <button type="button" id="btn1" class ="btn1"> btn1 </button>
 <button type="button" id="btn2" class="btn2"> btn2 </button>
 <script>          
             var statement= 1;
             if (statement== 1){
                    <button type="button" id="btn3" class="btn3"> btn3</button>
             }
                                  
 </script>

My html looks like this atm. But It doesnt work, even if my statement is 1=1. How can I achieve this working without a button click event or some interaction?

Solution

You could use document.write to directly write into the HTML output. (Mentioned by @Ivar in the comments) Just place the script where you want to write something.

<button type="button" id="btn1" class="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<script>
var statement = 1;
if (statement == 1) {
  document.write('<button type="button" id="btn3" class="btn3"> btn3</button>');
}
</script>

You can decide where to display the button by moving the script tag to the location where you want to insert it. See example.

However a more commonly used approach is to manipulate the DOM instead of "echoing" your result in JavaScript.

You could have a button and change it’s display state:

var statement = 1;
if (statement == 1) {
  document.querySelector("#btn3").style.display = "inline-block"
}
<button type="button" id="btn1" class="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<button type="button" id="btn3" class="btn3" style="display: none;"> btn3</button>

You could create a button and add it to the DOM:

const button = document.createElement("button")
button.type = "button"
button.id = "btn3"
button.classList.add("btn3") // Adds one class with the name btn3

button.textContent = "btn3" // Writes what is inside <button>....</button>

document.body.append(button) // Adds element below each other elements
<button type="button" id="btn1" class="btn1"> btn1 </button>
<button type="button" id="btn2" class="btn2"> btn2 </button>
<button type="button" id="btn3" class="btn3" style="display: none;"> btn3</button>

More about:

Answered By – Lars Flieger

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.