Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  132] [ 7]  / answers: 1 / hits: 7599  / 5 Years ago, tue, february 12, 2019, 12:00:00

In my HTML file I have a div with id=list.
Now I want to display a string from my javascript in my html. page. but nothning
happen. In my html file, i've imported the srcipt file. Here's how it looks in my script file:



var namesArray = [lars, bo, ib, peter, jan, frederik];

var list = namesArray.map(name=><li>+name+</li>);
var listAsStr =<ul> + list.join() + <ul>;
document.getElementById(list).innerHTML = listAsStr;

More From » html

 Answers
11

You need to put the JavaScript code after your dom and also wrapped with Script tag.



Example: This will work since we rendered the HTML first and then executed the js into it.





<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<title>This Will WorK</title>
</head>
<body>

<div id=list ></div>

<script>
var namesArray = [lars, bo, ib, peter, jan, frederik];

var list = namesArray.map(name=><li>+name+</li>);
var listAsStr =<ul> + list.join() + <ul>;

document.getElementById(list).innerHTML = listAsStr;
</script>
</body>
</html>





But this will NOT work since the JavaScript is being executed before dom rendered. Also this will probably throw an error Cannot set property 'innerHTML' of null because getElementById will not be able to find the associated dom.





<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=UTF-8>
<title>This Will Not WorK</title>
</head>
<body>

<script>
var namesArray = [lars, bo, ib, peter, jan, frederik];

var list = namesArray.map(name=><li>+name+</li>);
var listAsStr =<ul> + list.join() + <ul>;

document.getElementById(list).innerHTML = listAsStr;
</script>

<div id=list ></div>

</body>
</html>




[#8959] Monday, February 11, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryderalfonsos

Total Points: 655
Total Questions: 88
Total Answers: 91

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
ryderalfonsos questions
Mon, Sep 9, 19, 00:00, 5 Years ago
Wed, Feb 13, 19, 00:00, 5 Years ago
Fri, Dec 28, 18, 00:00, 6 Years ago
;