Understanding the process

Hi! Based on my question you will understand that my knowledge of JavaScript is pretty much basic. I have two questions that I need answered:
1.


//create a reference to h1
var headings = document.getElementsByTagName("h1");
var heading = headings[0];
//check if heading has a class called: red
var theClass = "red";
//create a regular expression
var pattern = new RegExp("(^|)" + theClass + "(|$)");
//make sure our element does not have a class: red
if (!pattern.test(heading.className))
{
	//it does not have the same class
	//if no class is assigned at all, add our class
	if (heading.className == "")
	{
		heading.className = theClass;
	}
	else
	{
		heading.className = heading.className + " " + theClass;
	}
}

Then I have .css file, let’s say with this contents:


.red {
	color:red;
}

My question is: when I look into html code of the page, an HTML element to which a class (.red) was added does not have such an attribute there, inside of the element. My logic (and I know it is wrong) tells me, I should see something like:


<h1 class="red">My heading level 1</h1>

But what I see is (same element but without a class attribute):


<h1>My heading level 1</h1>

Could someone please explain me why there is no class attribute in HTML element even though a class was added via JavaScript? Unfortunately, the book I am reading to learn JavaScript does not give enough theory on how browser handles JavaScript.
2. Another very basic question is:
For a purpose of reusing this code, there is a logical advantage of creating a couple of functions and using them when necessary. In a brief: how do I create a list of basic functions that I will be using, and link to that file containing this list of functions? Again, this is something the book does not explain?!:nono:
Detailed example:
I have a file called: core.js. Here is its contents with all of the functions that I will need to use:


// JavaScript Document
Core.getElementsByClassName = function(theClass)
{
	//create a node list of all elements
	var elementArray = [];
	//fix a bug for IE5.x that does not recognize * value for getElementsByTagName
	if (typeof document.all != "undefined")
	{
		elementArray = document.all;
	}
	else
	{
		elementArray = document.getElementsByTagName("*");
	}
	//create an array to collect all nodes that match our search criteria
	var matchedElements = [];
	//create a regular expression
	var pattern = new RegExp("(^|)" + theClass + "(|$)");
	//go through each node in our node list
	for (var i = 0; i < elementArray.length; i++)
	{
		if (pattern.test(elementArray[i].className))
		{
			matchedElements[matchedElements.length] = elementArray[i];
		}
	}
	return matchedElements;
};

Core.hasClass = function(target, theClass)
{
	var pattern = new RegExp("(^|)" + theClass + "(|$)");
	if (pattern.test(target.className))
	{
		return true;
	}
	return false;
};

Core.addClass = function(target, theClass)
{
	if (!Core.hasClass(target, theClass))
	{
		if (target.className == "")
		{
			target.className = theClass;
		}
		else
		{
		target.className += " " + theClass;
		}
	}
};

Then I have .html file, located in the same folder as core.js file


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript</title>
<link href="style.css" type="text/css" rel="stylesheet" media="all" />
</head>
<body>
	<div id="container">
        <h1>Some text</h1>
        <p>
		Some text
		</p>
        <p>
        Some text
        </p>
	</div>        
        <script type="text/javascript" src="core.js"></script>
        <script type="text/javascript" src="example.js"></script>
</body>
</html>

example.js is located in the same location as two other files that I mentioned.
I write all of the JavaScript code in example.js
Here is its contents:


var headings = document.getElementsByTagName("h1");
var heading = headings[0];
var theClass = "red";
Core.addClass(heading, theClass);

My heading does not become of class red. I am doing something wrong with linking to a library of this functions located in core.js file. What am I doing wrong? What is the right way to do it?
Just need to figure it out and any help to a stupid novice would be appreciated.
Alex.

  1. JavaScript code is run by the browser, after the HTML (and JavaScript) has been fully downloaded from the web server. When you “view source” in the browser, it shows you the HTML that it was sent. It never changes in response to any JavaScript that the browser ran. Only the internal representation of the document in memory is changed by the browser. It doesn’t need to rewrite the HTML text document to do that, so it doesn’t.

  2. It’s time to get familiar with a debugger. Get the Firebug extension for Firefox, or use the JavaScript Console built into Chrome.

Ok, a couple of things first:

a.) You’re not stupid. just new to a concept. Big difference, there. :slight_smile:
b.) We were ALL novices, once.
c.) The only stupid question is the one that is never asked.

Don’t feel bad about this situation. I figured out the same thing (and lost a lot of hair in the process) not all that long ago, when I was working with changing innerHTML on a div. Took me forever, too, but I finally figured out for myself that which Dan just pointed out.

I see from the code you posted that you’ve picked up some good habits, such as placing your scripts at the bottom of your HTML page. Good job. Keep that up. :smiley:

Thank you for your encouragement. Sometimes I feel I need lots of it!
Alex.

Thank you for your answers. I understand the 1st one now, speaking about the 2nd one… I can see the book I use has got a chapter describing that subject.

Thanks again,
Alex.

Actually, a little nitpick to what Dan posted. If you have JavaScript in the <head>, it is downloaded, parsed (interpreted) and run by the browser before whatever comes after it. This is a common pitfall for people who say, “why doesn’t my script work?”, not aware that the actual HTML they want to operate on is completely unknown to the JavaScript.

It is for this reason that pages with lots and lots of javascript in the head (common, nowadays with jQuery and its plugins, and such things) can appear to load very slowly, but it’s just because of all the extras being downloaded in the background.

If you want to see the HTML document after JavaScript has been run on it, in Firefox press Ctrl+A (select all) and then right-click and “view selection source”. You can of course also view the source just for a section of a document (very useful).

This is the reason why I love this site. I learn something new practically every time I visit. I wish I had known this months ago. :smiley:

Thank you so much for this tip! I did not know you could see the HTML affected by JavaScript! Thanks a lot! And for all of your input!
Alex.

Pleasure. :slight_smile:

You can even go one further - in Firebug you can see the HTML be affected by the JavaScript in real time!

Yeah, Firebug… I am getting there in a couple of chapters :slight_smile: