0

I've been trying to create a news box for my website today and I have a problem. Let me explain what happens. I create a 2d array that contains the news (date and the news). I then loop through it to construct the news_string and then use that for the DIV's innerHTML. I have put a very simple version of it below

for (var i = 0; i < news.length; i++) 
{
news_string.concat(news[i][1],"<br>");
}

document.getElementById("news-content").innerHTML = news_string;

However nothing appears. I have cut it down to the very minimal. No result. I have used alerts. Nothing appears. The news_string is blank regardless of the fact I put data into it. And even if I do gain a string nothing appears in the DIV box. What's causing this massive break?

7
  • 2
    Did you try alert(news.length)? Commented Feb 16, 2014 at 11:12
  • I did alert(news.length) and it is all normal. Commented Feb 16, 2014 at 11:13
  • However if I do this. news_string = news_string + news[i][1] + "<br>"; alert(news_string) The string completely appears Commented Feb 16, 2014 at 11:14
  • 4
    @JeremyBeare: Strings are immutable in JavaScript. news_string.concat returns a new string, so the code in your loop isn't really changing anything. Commented Feb 16, 2014 at 11:15
  • What about using news_string = news_string.concat(news[i][1],"<br>"); ? Commented Feb 16, 2014 at 11:16

1 Answer 1

1

The concat method returns a value, you have no variable assignement there to catch it...

From the docs (notice the bold part):

The concat() method combines the text of two or more strings and returns a new string.

So you should use:

news_string = news_string.concat(news[i][1],"<br>");
Sign up to request clarification or add additional context in comments.

18 Comments

Oh, pfft, how did I not notice that?
Or just news.map(function(thing) { return thing[1]; }).join('<br>').
Makes perfect sense. Can't believe I made that error. So the string now has values. However the problem still persists that the innerHTML is blank. This is the code I pass into the innerHTML document.getElementById("news-content").innerHTML = news_string;
@JeremyBeare, please post a sample of the array.
@JeremyBeare, in the inline javascript remove the (). refer just to the function loadNews in the parameter without the (). I missleaded you in my fast example before sorry. Check here: jsfiddle.net/C7nh3
|

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.