1

I want to print html code in Javascript code. I want to open and close the bottom line of five li tags. How can I do this with a for loop

jQuery(document).ready(function () {
   InsertLi();
});

function InsertLi(){
   var count = 5;
   for (var i = 0; i < count; i++) {
       var codeBlock = ' <li>' + i + '</li>';
       $(".bildirimMetin").html(codeBlock);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>

3 Answers 3

2

You need to use append function instead. html function every time overrides your html content with the new content and you get only the last one. Also create your string with 5 li-s and then call the append at the end to work with DOM one time and have more performance.

function InsertLi() {
   var count = 5;
   var codeBlock = '';
   for (var i = 0; i < count; i++) {
       codeBlock += ' <li>' + i + '</li>';
   }
   
   $(".bildirimMetin").append(codeBlock);
}

jQuery(document).ready(function () {
   InsertLi();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin"></ul>

If you have only one item with bildirimMetin class, it will be better to use id instead of class.

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

Comments

1

Well, another solution, close to your code, with html, store all strings in your variable via += then you must define your variable before for loop also move your html after it. Your current code not working because it just store last string not all.

InsertLi();

function InsertLi() {
  var count = 5;
  var codeBlock = '';
  
  for (var i = 0; i < count; i++) {
    codeBlock += '<li>' + i + '</li>';
  }
  
  $(".bildirimMetin").html(codeBlock);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bildirimMetin">
</ul>

Comments

1

you had a couple issues. One was overwriting the inner HTML instead of appending. The other was a syntax issue.

function InsertLi(){
 var count = 5;
    for (var i = 0; i < count; i++) {
        var codeBlock = ' <li>' + i + '</li>';
        $(".bildirimMetin").append(codeBlock);
   }
 }

jQuery(document).ready(function () {
InsertLi();
}
);

Comments

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.