Home > Back-end >  How to set condition for a class in a <div> in javascript
How to set condition for a class in a <div> in javascript

Time:10-13

I want to hide the div using d-none in bootstrap when the post.title is empty. I have tried so far and the card-body is still showing. There's no text but I don't want it to show at all. I am new to web dev in general so I really don't know how to achieve this. I am not sure my syntax is correct either. Any tips?

<div class = {${post.title} == '' ? "d-none" : "d-inline"}>
    <div >
         ${post.title}
                                       
    </div>
</div>

CodePudding user response:

<div class=`${post.title === '' ? "d-none" : "d-inline"}`>
   <div >
     `${post.title}`                                 
   </div>
</div>

Here I am using Template literals and ternary operator. Please have a look to both link. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

CodePudding user response:

You don't need bootstrap:

function hide(){
  document.getElementById("div").setAttribute("hide","true");
}
function show(){
  document.getElementById("div").setAttribute("hide","false");
}
[hide="true"]{
  display: none;
}
<div hide="true" id="div"><button onclick="hide();">X</button><p>So you want to hide a div? Bootstrap not needed! :)<p><img src="https://turtleonafencepostsite.files.wordpress.com/2017/08/fullsizerender.jpg?w=648" alt="Why Turtle on a Fence Post? – Turtle on a Fence Post"/></div>
<button onclick="show();">Show it</button>

  • Related