-1

My code is like this:

<script> 
    var name = document.getElementById("nusname").innerHTML;
    document.getElementById("uName").innerHTML = "Welcome, " + name;
    $('#uName').text("AsgufHFBS");
</script>

The 3rd line

document.getElementById("uName").innerHTML = "Welcome, " + name;

works but the 4th line

$('#uName').text("AsgufHFBS");

does not.

I have tried replacing this with

$(document).ready(function(){
    $('#uName').text("AsgufHFBS");
});

but it still does not work.

So my question is this: Why does the javascript work but the not the JQuery version?

JJJ
  • 135
  • 8

4 Answers4

4

Add this in the <head> of your document:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Or simply update your code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script> 
    var name = document.getElementById("nusname").innerHTML;
    document.getElementById("uName").innerHTML = "Welcome, " + name;
    $('#uName').text("AsgufHFBS");
</script>
DDan
  • 8,068
  • 5
  • 33
  • 52
  • @JamesTan you should wrap the code inside doc ready block or move this script block at the end of body. – Jai Aug 04 '15 at 11:23
0

Assuming that you have already embedded the jQuery library correctly and it's still not working, try this:

jQuery('#uName').text("AsgufHFBS");

If that works it means the $ shorthand is likely reserved by another script on your page. You can either correct that issue, or just preface jQuery commands with "jQuery" rather than "$" on that page.

Bangkokian
  • 6,548
  • 3
  • 19
  • 26
0

I have coded your code into jsFiddle and it works fine, however did you include jQuery in your file? If you press f12 in your browser do you get any console logs? If so please provide them.

But here is the jsFiddle version which does include jQuery

jsFiddle : https://jsfiddle.net/bn788ff4/

Html

<div id="nusname">hello</div>
<div id="uName">username</div>

Javascript / jQuery

var name = document.getElementById("nusname").innerHTML;
document.getElementById("uName").innerHTML = "Welcome, " + name;
$('#uName').text("AsgufHFBS");

To include jQuery you can use the hosted version by google

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

Link https://developers.google.com/speed/libraries/

Canvas
  • 5,779
  • 9
  • 55
  • 98
0

You are probably missing Jquery library files. Please attach the foolowing to the <head> section of your page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

and replace the 4th line of your code with:

$('#uName').html("AsgufHFBS"); 
Rajan Goswami
  • 769
  • 1
  • 5
  • 17