1

I'm beginning my adventure with the Javascript. I stuck in one part of my code. I would like to change assignations of file name to the src attribute in html element. I create the file name in a external function and then I pass it to the function setting new src attribute. I don't understand why it doesn't work. When I assign an exact file it works. Could someone explain it to me ? Below is the code:

index.html

<html>

<head>

<script type="text/javascript" src="navContent.js"></script>

</head>

<body>
  <nav>
   <ul>
    <li>
     <a href="#newFile" onclick="showDescriprion('newFile')">newFile</a>
    </li>
   </ul>
  </nav>

<p id="demo"></p>

<section class="description">
 <h2 id="nevTitle"></h2>
 <script id="nevDescript" src=none></script>
</section>

</body>

</html>

navContent.js

function showDescriprion(chosenNav){

  var idDescript = document.getElementById("nevDescript");

  document.getElementById("nevTitle").innerHTML=chosenNav;

  idDescript.setAttribute("src", chosenNav.toLowerCase().concat(".js"));

  //checking
  document.getElementById("demo").innerHTML=idDescript.getAttribute("src");
}

newfile.js

document.write(
 <dl>\
  <dt>Uni</dt>\
   <dd>Des</dd>\
 </dl>);

The problem is here: <script id="nevDescript" src=none></script>. When I write src="newfile.js" it works. I want to avoid doing the switch-case. That's why I'm doing the function showDescriprion(chosenNav)

Ania
  • 139
  • 1
  • 9
  • Is there any error on your console when clicking that link? – Pratansyah Nov 21 '17 at 00:34
  • 1
    Possible duplicate of [setting src of html – showdev Nov 21 '17 at 00:37
  • @Pratansyah no, there isn't. – Ania Nov 21 '17 at 00:45
  • It looks like setAttribute does not assign filename to src attribute – Ania Nov 21 '17 at 02:02

1 Answers1

1

What you are trying to do is adding a new script dynamically, try searching more information about it. You could start here - https://www.danielcrabtree.com/blog/25/gotchas-with-dynamically-adding-script-tags-to-html - you find some tips and also an warning that a document.write call won't work in this case(also, you forgot to use quotes). You can also look this previous question at Loading scripts after page load?, the answer that @Nicolas Bouvrette and @Johannes H. posted will not require the use of any additional library.