Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector not working

ive been trying to figure out why my JavaScript code will not work. The alert works fine, but when I try to write in a div it does nothing. What am I doing wrong? Ive been trying to google the answer, but that has not been too helpful.

 <!DOCTYPE html> 

<html>
<head>

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

<script src="gamejavascript.js" type="text/javascript"> </script>  

<link rel="stylesheet" type="text/css" href="gameStyle.css">

<title>Text Adventure RPG</title>   

</head>

<body>
<p>hey  </p>
    <div id="eventWindow">
        <div id="title">Black Forest</div>
        <div id="eventContent">You have entered the black forest. Lucky you!</div>
    </div>
    <div id="itemList">Hey hey hey </div> 

    <div id="userStat"> </div> 

</body>

</html>

My javascript is

$("p").append("HEY HEYH YEYEHE."); 
alert("You madam are a horse!");
$("#userStat").html("Hey baby"); 



/* var user = function(attack,health)
{
this.attack = attack; 
this.health = health;
}; 

var player = new user(10,100); */ 

thank you so much for your help!

-Brent

like image 827
Norbertle Avatar asked Feb 01 '14 21:02

Norbertle


People also ask

What is not selector in jQuery?

not selector Description: Selects all elements that do not match the given selector. version added: 1.0 jQuery (":not (selector)") selector: A selector with which to filter by. All selectors are accepted inside :not (), for example: :not (div a) and :not (div,a).

Why is jQuery click not working at the time page loading?

jQuery click not working at the time page loading, jQuery Onclick Method is tried to an element or selector. As a result, the binding will fail if the element we wish to click isn’t present when the page is ready.

What is the difference between not() and selectors in CSS?

selector: A selector with which to filter by. All selectors are accepted inside :not (), for example: :not (div a) and :not (div,a). The .not () method will end up providing you with more readable selections than pushing complex selectors or variables into a :not () selector filter. In most cases, it is a better choice.

Why is my JavaScript event handler not working?

The most typical cause for this code not working as intended is that the JavaScript gets placed and performed before the HTML element to which we are trying to add an event handler. When we know the full DOM tree has been built, the simplest method is adding the script code before the end tag.


1 Answers

You need to put your JavaScript at the end of the page before the closing body tag or in the head and wrapped in a document ready call. Ex:

$( document ).ready(function() {
    // your code here
});

jsFiddle example (placing code at end of document)

The way you have it now, you're trying to execute code on elements that don't yet exist.

like image 105
j08691 Avatar answered Oct 30 '22 07:10

j08691