skip to Main Content

Question: How to remove any JavaScript code (functions, variables, events etc.) which is Inside a Dom element (div)

Note: This is not similar question like removing content from Dom element.

My Scenario:

My site has a menu. When I click on a menu item I am loading corresponding html file which also contains JavaScript code inside a div element(id=content).
When click on menu I am doing following code

function changeMenu(params){
  //need something here to remove previous js codes before load the file
  $('#content').load(params['file'],function (){
        ///ohters code
    })
}

It is working fine for first click and executing the JavaScript code as well inside that file.
But problem is it also increase executing JavaScript code number of times I click on the menu. Also when I load another file still previous JavaScript code executing because I had interval function there. Aslo if there is variable declared like this let x=10
it showing follwing error when I click the menu again

Uncaught SyntaxError: Identifier ‘x’ has already been declared

Asking Solution:
Is it posible remove all JavaScript codes when I click on the menu and How?

Sample Code

index.html

<!doctype html>
<html lang="en">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    </head>
    <body>
        <header>
            <button onclick="changeMenu('a.html')">Load A</button>
            <button onclick="changeMenu('b.html')">Load B</button>
        </header>
        <div id="content">

        </div>
        <script>
            function changeMenu(file){
                $('#content').load(file,function (){
                    ///others code
                })
            }
        </script>
    </body>
</html>

a.html

This is A
<script>
    //let x=10;
    setInterval(() => {
        //code for A
        console.log("I am interval A 1st line")
        console.log("I am interval A 2nd line")
    }, 1000);
</script>

b.html

This is B
<script>
    //let x=10;
    setInterval(() => {
        //code for B
        console.log("I am interval B 1st line")
        console.log("I am interval B 2nd line")
    }, 1000);
</script>

Please Run the index.html,click the buttons and watch the console log.

2

Answers


  1. Even though this may not be a straightforward answer to your question,but you may want to try if this works as a workaround.

    1. Make all code to be inside a function. Even if you want to run some code at the time of loading the page, make it to be inside a function and call it immediately. Variables are accessible inside a particular function only unless you return it.
    2. Even if you are returning something from a function do it like this:(as an array or object).
    function Apple(){ let x=10; return [x];} //yes, inside an array, also can return multiple variables.
    

    and access it like this:

    function Book(){ let x=Apple[0];}
    
    Login or Signup to reply.
  2. Method .load() immediately places loaded data in element. That is, you can’t do anything with the html before pasting.

    You can use jQuery.get() method and remove all <script> tags before pasting. Something like this:

    <button onclick="changeMenu('a.html')">Load A</button>
    <button onclick="changeMenu('b.html')">Load B</button>
    
    <div id="content"></div>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script>
    function changeMenu(file) {
      $.get(file, function(html) {
        html = $('<div>' + html + '</div>');
        html.find('script').remove();
        $('#content').append(html);
      })
    }
    </script>
    

    DEMO

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search