1

here is a basic program, I don't understand why this is not working:

a object class, houseObject.js:

var string;

    function createSentence(paragraph){
        this.string = paragraph;
    }

    function getString(){

        return string;  
    }

The program for running:

<!DOCTYPE html>
<html>
<head>

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

   var temp = new createSentence("hello world");
   var string = temp.getString();
    var para=document.createElement("p");
    var node=document.createTextNode(string);
    para.appendChild(node);


</script>

</head>


<body>

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
    var element=document.getElementById("div1");
    element.appendChild(para);
</script>
</body>
</html>

My second question is: why cant I put

    var element=document.getElementById("div1");
    element.appendChild(para);

inside the head section of the html. Is it because html is a script program, it hasn't read the body section yet?

Thanks in advance

user308553
  • 1,108
  • 3
  • 15
  • 29
  • 1
    For a faster load and better performance you could put all the JS just before the end body tag. – Mr.Web Aug 05 '13 at 22:38
  • Ah I got your problem. When you put the script into `head`, the element `div1` doesn't exist (yet). Place your scripts in the end of your HTML, or [use window.load or document.DOMContentLoaded events](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). – metadings Aug 05 '13 at 23:19
  • @metadings, oh I did though, I made another script section right before the end of body section – user308553 Aug 05 '13 at 23:28
  • you would feel much more comfortable when using [`jQuery(document).ready`](http://api.jquery.com/ready/) - using jQuery also eliminates headaches about attachEvent/addEventListener, selecting elements by id, classes and other quirks – metadings Aug 05 '13 at 23:31

4 Answers4

2

I'm afraid you haven't quite grasped how objects work in Javascript works. this.name is not the same as name which you appear to define globally. Read more about objects in Javascript at "Introduction To Object Oriented Javascript".

Leonard
  • 2,852
  • 2
  • 27
  • 49
2

You can build a constructor function to get an object back:

var Sentence = function (text) {
    this.text = text;
};

Now if you do

var obj = new Sentence("Hello World");

You have an obj instanceof Sentence and you can access the property like

console.log(obj.text); // prints Hello World

To "attach" this to a DOM element is a huge other answer. See this question why it's dangerous to reference the object directly on a DOMElement. Maybe you should start with jQuery.data or you make an array or another object for storing id/object tuples:

var list = [ obj0, obj1 ];

var keyValueStore = { "key0": obj0, "key1" : obj1 };

Further extending the constructor function and it's object instances:

var Sentence = function (text) {
    this.para = document.createElement("p");
    this.setText(text);
};

Sentence.prototype.setText = function (text) {
    if (this.node) {
        this.para.removeChild(this.node);
    }
    this.node = document.createTextNode(text);
    this.para.appendChild(this.node);
};

Sentence.prototype.getText = function () {
    if (this.node) {
        if (!this.node.textContent) {
            // typical IE hack
            return this.node.innerText;
        }
        return this.node.textContent;
    }
};

Usage:

window.onload = function () {

    var sentence0 = new Sentence("Hello World");

    document.body.appendChild(sentence0.para);

    setTimeout(function () {
        sentence0.setText("I'm Edward!");
    }, 5000);

};

Fiddle: http://jsfiddle.net/tfets/ (jsFiddle does auto-wrap a window.load handler).

Community
  • 1
  • 1
metadings
  • 3,638
  • 2
  • 25
  • 36
1

You are correct. HTML documents are read sequentially, and JS code is executed when found. A script inside <head> cannot access nodes inside <body>, because they haven't been read yet.

slezica
  • 63,258
  • 20
  • 91
  • 152
1

Ok, if you are working with Objects use Prototype, like this:

function createSentence(paragraph){
    this.paragraph = paragraph;
}

createSentence.prototype.getString = function(){
    alert(this.paragraph);
    //Or return this.paragraph
}

var string_1 = new createSentence('my sentence');
var string_2 = new createSentence('another sentence');

string_1.getString();
//Will return 'my sentence'

string_2.getString();
//Will return 'another sentence'
Mr.Web
  • 5,891
  • 8
  • 37
  • 75