简体   繁体   中英

Can you declare/place a html element tag inside a variable?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM