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)

4
  • Is there any error on your console when clicking that link? Commented Nov 21, 2017 at 0:34
  • 1
    Possible duplicate of setting src of html <script> in javascript OR Changing “src” attribute of <script> Commented Nov 21, 2017 at 0:37
  • @Pratansyah no, there isn't. Commented Nov 21, 2017 at 0:45
  • It looks like setAttribute does not assign filename to src attribute Commented Nov 21, 2017 at 2:02

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.