0

hello i am trying to get a function in a script folder to work on an html page

I have this set up html

<script src="add.js">

txt = document.createElement('p')
document.body.appendChild(txt)
txt.innerHTML = add(2);


</script>

and script file function

function add(a){
return a+a
}

Its not working and im not sure why. i have tried wrapping the whole statements inside a function and calling that. tried onload in different positions and didnt work.

thank you

proger
  • 45
  • 7
  • 2
    Does this answer your question? [What does a script-Tag with src AND content mean?](https://stackoverflow.com/questions/6528325/what-does-a-script-tag-with-src-and-content-mean). Related: [Script tag with both external source and body](https://stackoverflow.com/q/8676093/4642212). – Sebastian Simon Mar 23 '21 at 22:04
  • its not rendering results on the browser – proger Mar 23 '21 at 22:04
  • 1
    because that's not legal script use. Put all your JS _in your .js file_, but remember to load it as `` so that you script only runs _after_ the DOM has finished parsing. Finally, don't use `innerHTML` unless you actually need to (unsafely) inject HTML code. If you just want to set text, use `textContent = ...` instead. – Mike 'Pomax' Kamermans Mar 23 '21 at 22:07
  • That first script-tag one is not a dupe, that is something else – epascarello Mar 23 '21 at 22:12

1 Answers1

1

As Mike said in the comments you can't write your script that way

Two ways to solve it

1:

<script src="add.js"></scirpt>
<script>
    //...Code here
</script>

2: preferred:

<script>
    txt = document.createElement('p');
    document.body.appendChild(txt);
    txt.innerHTML = add(2);

    function add(a){
        return a+a;
    }
</script>
silversunhunter
  • 1,219
  • 2
  • 12
  • 32