0

I don't understand why simple code is not working is my browser.

    <head>
     <script src="../static/js/jquery-1.12.3.min.js" ></script>
    <script src="../static/js/jquery-ui.min.js"></script>
    <link href="../static/js/jquery-ui.min.css" rel="stylesheet"/>
    <script>
     $("#totalCart").html("99,75");
    </script>  
   </head>

<body>
 <div id="totalCart">Total </div>
</body>

when I start this code in Chrome I see nothing, why?

Alex As
  • 9
  • 4
  • 2
    Use document ready handler, read https://learn.jquery.com/using-jquery-core/document-ready/ – Satpal Aug 01 '16 at 07:27
  • check browser console . if any error here you find the error – tapos ghosh Aug 01 '16 at 07:28
  • Hit F12 and go to the Console and Network tabs. Any errors? Also, your script is run before the element in your HTML is created. Either put the Javascript at the bottom of the file (before `

    `) or use jQuery's [`.ready()` method](https://api.jquery.com/ready/).

    – Sverri M. Olsen Aug 01 '16 at 07:30
  • have a look at this answer: http://stackoverflow.com/a/23476758/2008111 – caramba Aug 01 '16 at 07:30
  • @taposghosh — There won't be an error. jQuery fails silently. – Quentin Aug 01 '16 at 07:30
  • @caramba — That's a red herring since all the discussion is about performance and not the problem the OP is experiencing. (And it isn't great for performance either since it prevents parallel downloading). – Quentin Aug 01 '16 at 07:31
  • browser in view page source check all your js file loading correctly or not – tapos ghosh Aug 01 '16 at 07:32
  • @taposghosh — You seem to be confusing the page source code with the Network tag in the browser's developer tools. – Quentin Aug 01 '16 at 07:37

2 Answers2

2

You're using a selection before DOM is loaded.

The good practice is to include all script at the end of your body.

Or you can use

$(document).ready(function(){
  //your code
});
Alexis
  • 5,217
  • 1
  • 22
  • 42
0

Try putting

<script>
$("#totalCart").html("99,75");
</script>

just before

</body>

Explanation:

For jQuery to grab an element via $("#totalCart") - and, likewise, for non-library javascript to grab an element via document.getElementById('totalCart') - that element has to first exist.

In your original structure, the script runs as soon as it is parsed - but this happens before the element is parsed... effectively, at the moment the script runs, the element does not yet exist.

By the time the element is parsed and does exist, the script has already run and it is not invoked a second time.

If you place the <script> at the very end of the document (just before <body>) then all elements will already have been parsed by the browser rendering engine and they will exist.

Rounin
  • 21,349
  • 4
  • 53
  • 69