1

I'm currently using w3schools for javascript. I've done some js work on freecodecamp but I came across something on w3schools that I'm not familiar with and would be nice if someone could explain to me why this works.

The text variable declares "ul", it is also used inside the for loop code block (if that's what you call it), and also used again after the for loop.

It clearly works but I can't get my head round it even though it seems so simple.

I know because it's a script tag and you can't directly use the html tags, but how does the computer know to use an unordered list, followed by list item when it's quoted in quotation marks. If that makes sense.

<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;

let text = "<ul>";
for (let i = 0; i < fLen; i++) {
  text += "<li>" + fruits[i] + "</li>";
}
text += "</ul>";

document.getElementById("demo").innerHTML = text;
</script>
  • 2
    You are using `string concatenation` in your `for` loop and after your `for` loop, essentially just appending to your variable. When you set this to the `innerHTML` the browser then parses it as HTML. Read more about string concatenation here: [Strings](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Strings) – Ryan Wilson Jul 06 '22 at 18:03
  • 1
    It's just building a string of HTML. The browser understands HTML. – VLAZ Jul 06 '22 at 18:03
  • https://stackoverflow.com/questions/2946656/advantages-of-createelement-over-innerhtml – j08691 Jul 06 '22 at 18:05

1 Answers1

1

Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string.

// the browser parses the HTML in the string and renders it as HTML elements.
element.innerHTML = '<h1>Hello World</h1>';

Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the element's descendants. The resulting string is returned.

When getting the value, the browsers serializes ( converts to string ) the html of the element.

element.innerHTML

innerHTML docs

If you don't want the browser to parse the HTML present in the string then you can use textContent.

// the browser will not parse the HTML in this string.
element.textContent = '<h1>Hello World</h1>';

textContent docs

Khalil
  • 1,495
  • 6
  • 14