0

I have this html file in which I want to display an ordered list.the list comes from an array which is in a js file and every time I use "src" to connect the two documents I keep getting an error saying the arrays in the js file have been declared which they have not been. HTML code

<div id=fruit>
      <h3>Displaying Fruits</h3>

      <script src="js/list.js">

         var list = document.createElement('ol');
         fruits.forEach(function (element){
           var li = document.createElement('li');
           li.textContent = element;
           list.appendChild(li);
         });
         var fruit = document.querySelector('#fruit');
         fruit.appendChild(list);
      </script>
    </div>

JS code

const fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos'];

error

Uncaught SyntaxError: Identifier 'fruits' has already been declared at VM13 list.js:1

1
  • 1
    can you include list.js - also you should load up your list.js as a script and then have a separate script tag for your html javascript Commented Feb 28, 2020 at 12:18

1 Answer 1

3

See, any script tag which has a src attribute, ignores all the content written inside the script block. So, you might need to add one more script tag:

<script src="js/list.js"></script>
<script>
  var list = document.createElement('ol');
  fruits.forEach(function(element) {
    var li = document.createElement('li');
    li.textContent = element;
    list.appendChild(li);
  });
  var fruit = document.querySelector('#fruit');
  fruit.appendChild(list);
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

thank you it worked but the error is still there. it still says fruits has been declared
at first look it seems that you have multiple fruits declarations in your js file.
I have looked at the js file and theres only one but its ok, I will ask my teacher thank you for your help.

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.