3

I have code working fine but I wanna simplify:

<script type="text/javascript">

   function RenderPager(items) {

      for (var i = 0; i < items.length; i++) {

         var li = "<li";

         if(i == 0){
            li += " class='first'";
         }

         li +=">" + i + "</li>";

         // do something else
      }
   }
</script>

I would like to have condition inline something like this:

   for (var i = 0; i < items.length; i++) {

       var li = "<li" + if(i == 0){ li += " class='first'" }; + ">" + i + "</li>";

       // do something else
   }

But this is not working and I tried everything but I don't know how to combine javascript condition in text variable. Is it possible?

1 Answer 1

6

You can use the conditional operator (?..:), also known as the ternary operator:

var li = "<li" + (i == 0 ? " class='first'" : "") + ">" + i + "</li>";

Also note, this could probably also be done using a little CSS with the :fist-child pseudo-class, but it's not supported by older versions of IE. See this compatibility chart:

li:first-child {
    /* applies only to the first <li> element in a list */
}
Sign up to request clarification or add additional context in comments.

1 Comment

Alternatively this shorter version would work also (!i && ' class="first"' || '').

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.