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)
-
Is there any error on your console when clicking that link?Pratansyah– Pratansyah2017年11月21日 00:34:58 +00:00Commented Nov 21, 2017 at 0:34
-
1Possible duplicate of setting src of html <script> in javascript OR Changing "src" attribute of <script>showdev– showdev2017年11月21日 00:37:04 +00:00Commented Nov 21, 2017 at 0:37
-
@Pratansyah no, there isn't.Ania– Ania2017年11月21日 00:45:57 +00:00Commented Nov 21, 2017 at 0:45
-
It looks like setAttribute does not assign filename to src attributeAnia– Ania2017年11月21日 02:02:21 +00:00Commented Nov 21, 2017 at 2:02
1 Answer 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.