1

I have a javascript function where i return a html code. In that piece of return statement i want to use if conditions. Please guide me how to use that.

This is my javascript function:

function abc(param)
{
  var step =2;
  if(n>0){

    return `
        <div>
        **{% if step == '1' %}
          <div class="box" style="background-color:red" id="prodcolor">
           <span style="display:none"> Sample</span>
          </div>
        {% endif %}**
        </div>
    `;

  }
}

I have highlighted the place where i have used if statement. This is my javascript file.

2 Answers 2

2

Use different strings for different conditions:

function abc(param)
{
  var step =2;
  if(n>0){

    return step == '1' ? `
        <div>
          <div class="box" style="background-color:red" id="prodcolor">
           <span style="display:none"> Sample</span>
          </div>
        </div>
    `:"<div></div>"

  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

is it possible to target the placed HTML return like changing a class later or moving it in the DOM?
0

You can use string concatenation. Btw, I'm assuming n is global variable here somewhere.

var n = 1

function abc(param)
{
  var step = 2;
  var innerHtml = '';
  if(n>0){
    if (step == '1') {
      innerHtml = `
          <div class="box" style="background-color:red" id="prodcolor">
           <span style="display:none"> Sample</span>
          </div>
      `;
    }
    return `
        <div>
        ${innerHtml}
        </div>
    `;

  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.