0

I have an array of strings, which I loop through and display the string and their respective div, But the strings have HTML, and I would like them to be actual HTML and not a string of text like they are currently being displayed.

My HTML :

<div class="line__0"></div>
<div class="line__1"></div>
<div class="line__2"></div>

jQuery :

var textLines = [
  "Line <strong>0</strong>.",
  "Line <strong>1</strong>.",
  "Line <strong>1</strong>."
];

function text(i) {
  for (i = 0; i < textLines.length; i++) {
    $('.line__' + i).html(textLines[i]);

  }
}
2
  • 1
    Provide MCVE. Your code would already set it as HTML content, not string. That's said, passing i to text() method doesn't make sense here because anyway you are redefining i in loop declaration, even it shoudl be: for (var i = 0;...). That's said, you don't need any for loop here: jsfiddle.net/nqj30mz0/1 Commented Jan 30, 2016 at 9:29
  • why you have made text() function. just put loop outside function or call that function Commented Jan 30, 2016 at 9:29

1 Answer 1

1

Why are you using the function text, it can be done without it just by putting your code directely inside the ready function :

var textLines = [
  "Line <strong>0</strong>.",
  "Line <strong>1</strong>.",
  "Line <strong>2</strong>."
];

for (i = 0; i < textLines.length; i++) {
  $('.line__' + i).html(textLines[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="line__0"></div>
<div class="line__1"></div>
<div class="line__2"></div>

Or you can use the function without passing any parameter, just text() :

var textLines = [
  "Line <strong>0</strong>.",
  "Line <strong>1</strong>.",
  "Line <strong>2</strong>."
];

function text() {
   for (i = 0; i < textLines.length; i++) {
       $('.line__' + i).html(textLines[i]);
   }
}

text();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="line__0"></div>
<div class="line__1"></div>
<div class="line__2"></div>

Hope this helps.

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

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.