JavaScript Function which counts number of DOM elements - javascript

I need to write a function which counts types of elements in the DOM
function setNumbers(){
var a = 0;
var b = 0;
var c = 0;
var d = 0;
var span = document.createElement('span');
span.style.background = 'black';
var anchors = document.getElementById('anchors');
var buttons = document.getElementById('buttons');
var text = document.getElementById('text');
var events = document.getElementById('events');
var elements = document.getElementsByTagName("*");
for(var i =0; i<elements.length; i++){
if (elements[i].nodeName === 'A') {
a++;
span.innerHTML = "anchors - " + a;
span.style.border = '1px solid yellow';
span.style.color = 'yellow';
anchors.appendChild(span);
}
if (elements[i].nodeName === 'TEXTAREA' || elements[i].nodeName === 'INPUT' ) {
b++;
span.innerHTML = "textfields - " + b;
span.style.border = '1px solid orange';
span.style.color = 'orange';
text.appendChild(span);
}
if (elements[i].nodeName === 'BUTTON') {
c++;
span.innerHTML = "buttons - " + c;
span.style.border = '1px solid green';
span.style.color = 'green';
buttons.appendChild(span);
}
if (elements[i].onclick) {
d++;
span.innerHTML = "events - " + d;
span.style.border = '1px solid pink';
span.style.color = 'pink';
events.appendChild(span);
}
}
}
setNumbers();
Here is the code. The function has to append the number of elements in relevant div, but appends only textarea elements. Can you please check my function and tell where I missed something? Thanks
Here is the fiddle

You use the same span variable across the scope, so it is override everytime. The last element in your HTML matching if is textarea, so it is the last type being counted.
Shortest fix: remove span and use this instead:
if (elements[i].nodeName === 'A') {
a++;
anchors.innerHTML = "anchors - " + a;
anchors.style.border = '1px solid yellow';
anchors.style.color = 'yellow';
}
PS: better idea would be to create a function counting elements of a specified kind (eg. setNumbers(type)), now you repeat yourself many times and use global selector * choosing all the items, even though you need only these matching a, textarea etc.

Try this out:- http://jsfiddle.net/acguvd4f/8/
JS:-
function setNumbers(){
var a = 0;
var b = 0;
var c = 0;
var d = 0;
var anchors = document.getElementById('anchors');
var buttons = document.getElementById('buttons');
var text = document.getElementById('text');
var events = document.getElementById('events');
var elements = document.getElementsByTagName("*");
for(var i =0; i<elements.length; i++){
var span = document.createElement('span');
span.style.background = 'black';
if (elements[i].nodeName === 'A') {
a++;
span.innerHTML = "anchors - " + a;
span.style.border = '1px solid yellow';
span.style.color = 'yellow';
anchors.appendChild(span);
}
if (elements[i].nodeName === 'TEXTAREA' || elements[i].nodeName === 'INPUT' ) {
b++;
span.innerHTML = "textfields - " + b;
span.style.border = '1px solid orange';
span.style.color = 'orange';
text.appendChild(span);
}
if (elements[i].nodeName === 'BUTTON') {
c++;
span.innerHTML = "buttons - " + c;
span.style.border = '1px solid green';
span.style.color = 'green';
buttons.appendChild(span);
}
if (elements[i].onclick) {
d++;
span.innerHTML = "events - " + d;
span.style.border = '1px solid pink';
span.style.color = 'pink';
events.appendChild(span);
}
}
}
setNumbers();

Related

Can we use multiple text color for same textbox? [duplicate]

I have an input text field like this,
input {
color: red
}
Name:
<input type="text" name="text" class="text" />
I want to apply different color for each letter in the input text field , If the user enters hai the each letter h,a,i the adjacent letter should have different color .Let me choose red and yellow. Is there is any way for that in jQuery, css?
http://jsfiddle.net/DerekL/Y8ySy/
$("body").prop("contentEditable", true).blur(function(){
var chars = $(this).text().split("");
this.innerHTML = "";
$.each(chars, function(){
$("<span>").text(this).css({
color: "#"+(Math.random()*16777215|0).toString(16) //just some random color
}).appendTo("body");
});
});
You can actually set the event to keypress if the user is only going to enter with a normal keyboard. I used blur here because keypress/keyup will break the code if the user is entering text with IME.
As Billy Mathews mentioned, one might want to have an input that can be submitted by form. Here is a solution:
<input type="hidden" id="hiddenEle">
var chars = $(this).text().split("");
$("#hiddenEle").val($(this).text());
this.innerHTML = "";
Just for fun
Here is one that won't change color: http://jsfiddle.net/DerekL/A7gL2/
Why not make the input's font invisible and have some javascript that dynamically changes some text placed over the input as you type? Something like this:
<div>
Name:<input type="text" name="text" class="text" />
<div class="colors"></div>
</div>
JavaScript:
$(document).ready(function(){
$('.text').keyup(function(){
var output="";
var letters = $(this).val().split("");
letters.forEach(function(letter){
var color = "#"+(Math.random()*16777215|0).toString(16);
//Stolen from Derek's answer ;)
output += '<span style="color: ' + color + ';">' + letter + '</span>';
$('div.colors').html(output);
});
});
});
Then you just gotta position the div over the input; et voila! Not tested.. but I am making a jsFiddle now! http://jsfiddle.net/pranavcbalan/54EY4/6/
Update: Fixed the CTRL+A DEL problem. FIDDLE
var input = document.getElementById("input");
input.onkeydown = colorTheText;
function generateRandomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random()*250));
}
return color;
}
function rgbToHex(color) {
var hex = [];
for (var i = 0; i < 3; i++) {
hex.push(color[i].toString(16));
if (hex[i].length < 2) { hex[i] = "0" + hex[i]; }
}
return "#" + hex[0] + hex[1] + hex[2];
}
function setEndOfContenteditable(contentEditableElement) {
var range,selection;
if(document.createRange) {
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
}
var colors = [];
var inputLength = 0;
var ctrl = [];
function colorTheText(e) {
if (e.keyCode == 8) {
if (ctrl.indexOf(17) > -1 && ctrl.indexOf(65) > -1) {
input.innerHTML = "";
ctrl.length = 0;
}
} else {
var text = input.innerText;
if (text.length > inputLength) {
inputLength++;
colors.push(generateRandomColor());
} else {
inputLength--;
colors.pop();
}
input.innerHTML = "";
text = text.split("");
for (var i = 0; i < text.length; i++) {
if (colors[i]) {
input.innerHTML += '<span style="color:' + rgbToHex(colors[i]) + '">' + text[i] + '</span>';
}
}
setEndOfContenteditable(input);
if (e.keyCode == 17) {
ctrl.length = 0;
ctrl.push(17);
}
if (e.keyCode == 65) {
if (ctrl[0] == 17 && ctrl.length == 1) {
ctrl.push(65);
}
}
}
}
Even though the question is answered, I wanted to post my answer. Might come handy to future viewers.
In this one color change happens while typing, and it remembers the color order until the div is completely cleared.
And I know it's not perfect. Yet. Play with it.
FIDDLE
setEndOfContenteditable function taken from Nico Burn's answer.
var input = document.getElementById("input");
input.onkeydown = colorTheText;
function generateRandomColor() {
var color = [];
for (var i = 0; i < 3; i++) {
color.push(Math.floor(Math.random()*250));
}
return color;
}
function rgbToHex(color) {
var hex = [];
for (var i = 0; i < 3; i++) {
hex.push(color[i].toString(16));
if (hex[i].length < 2) { hex[i] = "0" + hex[i]; }
}
return "#" + hex[0] + hex[1] + hex[2];
}
function setEndOfContenteditable(contentEditableElement) {
var range,selection;
if(document.createRange) {
range = document.createRange();
range.selectNodeContents(contentEditableElement);
range.collapse(false);
selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
}
var colors = [];
var inputLength = 0;
function colorTheText(e) {
var text = input.innerText;
if (text.length > inputLength) {
inputLength++;
colors.push(generateRandomColor());
} else {
inputLength--;
colors.pop();
}
input.innerHTML = "";
text = text.split("");
for (var i = 0; i < text.length; i++) {
if (colors[i]) {
input.innerHTML += '<span style="color:' + rgbToHex(colors[i]) + '">' + text[i] + '</span>';
}
}
setEndOfContenteditable(input);
}

blogspot.com List of all posts of the same tag

I created a new page on my blog and I would like to add there a list of all posts which include the same tag. For example: the tag name is "game" and I am looking for an JavaScript which will list all posts with images that contain tag "game".
Here I have already a code that lists popular posts:
<div class="widget-slimecuty-popular-posts">
<ul id="popular-li-container" style="list-style-type: none; padding: 0;">
<script type="text/javascript">
function loadXML(url) {
var xmlRequest = new XMLHttpRequest();
xmlRequest.onreadystatechange = function () {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
parseResponse(xmlRequest);
}
};
xmlRequest.open("GET", url, true);
xmlRequest.send();
}
function parseResponse(xml) {
var txtData = xml.responseText;
var parserDiv = document.createElement("div");
parserDiv.innerHTML = txtData;
var posts = parserDiv.getElementsByTagName("entry");
for (var i = 0; i < posts.length; i++) {
var links = posts[i].getElementsByTagName("link");
for (var j = 0; j < links.length; j++) {
if (links[j].getAttribute("rel") == "alternate") {
makeContainer(i);
var title = links[j].getAttribute("title");
var link = links[j].getAttribute("href");
makeTitle(title, i);
makeLink(link, i);
var content = posts[i].getElementsByTagName("content");
if (content.length == 0) break;
var parserContentDiv = document.createElement("div");
parserContentDiv.innerHTML = content[0].innerText;
var imgs = parserContentDiv.getElementsByTagName("img");
if (imgs.length == 0) break;
var imgurl = imgs[0].getAttribute("src");
makeImage(imgurl, i);
break;
}
}
}
}
function makeContainer(num) {
var li = document.createElement("li");
li.style.padding = "0";
var div = document.createElement("div");
var table = document.createElement("table");
table.style.width = "100%";
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.style.height = "72px";
td1.style.verticalAlign = "middle";
var td2 = document.createElement("td");
td2.style.width = "100%";
td2.style.verticalAlign = "middle";
var a1 = document.createElement("a");
a1.id = "popular-img-" + num;
a1.href = "javascript: void(0)";
a1.target = "_blank";
var a2 = document.createElement("a");
a2.id = "popular-title-" + num;
a2.href = "javascript: void(0)";
a2.target = "_blank";
a2.style.fontSize = "15pt";
td1.appendChild(a1);
td2.appendChild(a2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
div.appendChild(table);
li.appendChild(div);
document.getElementById("popular-li-container").appendChild(li);
}
function makeLink(link, num) {
document.getElementById("popular-title-" + num).setAttribute("href", link);
document.getElementById("popular-img-" + num).setAttribute("href", link);
}
function makeTitle(title, num) {
document.getElementById("popular-title-" + num).innerText = title;
}
function makeImage(imgurl, num) {
var img = document.createElement("img");
img.style.border = "1px solid black";
img.style.width = "72px";
img.style.height = "72px";
img.style.backgroundImage = "url('" + imgurl + "')";
var image = new Image();
image.src = imgurl;
if (image.width > image.height)
img.style.backgroundSize = "auto 100%";
else
img.style.backgroundSize = "100% auto";
img.style.backgroundPosition = "50% 50%";
img.style.backgroundRepeat = "no-repeat"
img.style.display = "inline-block";
img.style.maxWidth = "none";
document.getElementById("popular-img-" + num).appendChild(img);
}
function getPopularData() {
var url = "/feeds/posts/default?orderby=published";
loadXML(url);
}
window.onload = getPopularData;
</script>
</ul>
</div>
I tried to change this code, however without programming experience in JavaScript with blogger I couldn't do much.
To get blog posts for a specific label by XML feed (as in your code) use this url
http://yourBlogUrl/feeds/posts/default/-/LabelName
In Your code:
Replace var url = "/feeds/posts/default?orderby=published";
With var url = "/feeds/posts/default/-/game";
Note: Blogger labels are case sensitive, "game" different from "Game"
<div class="widget-slimecuty-popular-posts">
<ul id="popular-li-container" style="list-style-type: none; padding: 0;">
<script type="text/javascript">
function loadXML(url) {
var xmlRequest = new XMLHttpRequest();
xmlRequest.onreadystatechange = function () {
if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
parseResponse(xmlRequest);
}
};
xmlRequest.open("GET", url, true);
xmlRequest.send();
}
function parseResponse(xml) {
var txtData = xml.responseText;
var parserDiv = document.createElement("div");
parserDiv.innerHTML = txtData;
var posts = parserDiv.getElementsByTagName("entry");
for (var i = 0; i < posts.length; i++) {
var links = posts[i].getElementsByTagName("link");
for (var j = 0; j < links.length; j++) {
if (links[j].getAttribute("rel") == "alternate") {
makeContainer(i);
var title = links[j].getAttribute("title");
var link = links[j].getAttribute("href");
makeTitle(title, i);
makeLink(link, i);
var content = posts[i].getElementsByTagName("content");
if (content.length == 0) break;
var parserContentDiv = document.createElement("div");
parserContentDiv.innerHTML = content[0].innerText;
var imgs = parserContentDiv.getElementsByTagName("img");
if (imgs.length == 0) break;
var imgurl = imgs[0].getAttribute("src");
makeImage(imgurl, i);
break;
}
}
}
}
function makeContainer(num) {
var li = document.createElement("li");
li.style.padding = "0";
var div = document.createElement("div");
var table = document.createElement("table");
table.style.width = "100%";
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.style.height = "72px";
td1.style.verticalAlign = "middle";
var td2 = document.createElement("td");
td2.style.width = "100%";
td2.style.verticalAlign = "middle";
var a1 = document.createElement("a");
a1.id = "popular-img-" + num;
a1.href = "javascript: void(0)";
a1.target = "_blank";
var a2 = document.createElement("a");
a2.id = "popular-title-" + num;
a2.href = "javascript: void(0)";
a2.target = "_blank";
a2.style.fontSize = "15pt";
td1.appendChild(a1);
td2.appendChild(a2);
tr.appendChild(td1);
tr.appendChild(td2);
table.appendChild(tr);
div.appendChild(table);
li.appendChild(div);
document.getElementById("popular-li-container").appendChild(li);
}
function makeLink(link, num) {
document.getElementById("popular-title-" + num).setAttribute("href", link);
document.getElementById("popular-img-" + num).setAttribute("href", link);
}
function makeTitle(title, num) {
document.getElementById("popular-title-" + num).innerText = title;
}
function makeImage(imgurl, num) {
var img = document.createElement("img");
img.style.border = "1px solid black";
img.style.width = "72px";
img.style.height = "72px";
img.style.backgroundImage = "url('" + imgurl + "')";
var image = new Image();
image.src = imgurl;
if (image.width > image.height)
img.style.backgroundSize = "auto 100%";
else
img.style.backgroundSize = "100% auto";
img.style.backgroundPosition = "50% 50%";
img.style.backgroundRepeat = "no-repeat"
img.style.display = "inline-block";
img.style.maxWidth = "none";
document.getElementById("popular-img-" + num).appendChild(img);
}
function getPopularData() {
var url = "/feeds/posts/default/-/LabelName";
loadXML(url);
}
window.onload = getPopularData;
</script>
</ul>
</div>

Add onclick event to individual divs within loop

I am making a tic-tac-toe game.
I would like to add individual onclick event to each div so I can add either an "X" or an "O" depending on the div I click. "O" will be added later.
JavaScript:
function createDivs() {
for (i = 0; i < 9; i++) {
var d = document.createElement("DIV");
document.body.appendChild(d);
//Stuck here -borrowed some of this from a similar topic-
d.onclick = function() {
return function() {
var p = document.createElement("P");
var x = document.createTextNode("X");
p.appendChild(x);
d.appendChild(p);
}
}(i);
//-------------------------------------------------
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
html: <body onload="createDivs()">
Pass d as argument and accept it as argument so that closure will remember it when click handler-function will be executed.
d is nothing but the element you are creating(var d = document.createElement("DIV");)
function createDivs() {
for (i = 0; i < 9; i++) {
var d = document.createElement("DIV");
d.style.float = 'left';
document.body.appendChild(d);
d.onclick = function(d) {
//----------------^^^ Accept d here
return function() {
var p = document.createElement("P");
var x = document.createTextNode("X");
p.appendChild(x);
d.appendChild(p);
d.onclick = function() {}; //Unset function after click event
}
}(d);
//^^ Pass d here
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
div {
width: 30px;
height: 30px;
border: 1px solid black;
}
<body onload="createDivs()">
Update: As suggested by Barmar in comments, value of this in the event-handler function will be the element on which event registered.
function createDivs() {
for (i = 0; i < 9; i++) {
var d = document.createElement("DIV");
d.style.float = 'left';
document.body.appendChild(d);
d.onclick = function() {
var p = document.createElement("P");
var x = document.createTextNode("X");
p.appendChild(x);
this.appendChild(p);
this.onclick = function() {}; //Unset function after click event
};
var ii = document.createAttribute("id");
ii.value = "D" + i;
d.setAttributeNode(ii);
var z = "D" + i;
if (i == 3 || i == 6) {
document.getElementById(z).style.clear = "left";
}
}
}
div {
width: 30px;
height: 30px;
border: 1px solid black;
}
<body onload="createDivs()">

how to extract value of an input element in javascript

Please I want to extract the value of the input form with id input-a but the program keeps writing c instead of the value entered by the user. Please help. This is the JavaScript code.
< body>
<script>
function tableCreate() {
var body = document.body,
tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '2px solid black';
var n = 5
for (var i = 0; i < n; i++) {
var tr = tbl.insertRow();
var td =tr.insertCell(0);
var tf = tr.insertCell(0);
var input = document.createElement('input');
input.name = "input-a" + i;
input.id = "input-a" + i;
input.value = "";
var clone = input.cloneNode();
clone.name = "input-b" + i;
clone.id = "input-b" + i;
td.appendChild(clone);
tf.appendChild(input);
td.style.border = '2px solid black';
tf.style.border = '2px solid black';
}
var form = document.createElement("form");
form.appendChild(tbl);
body.appendChild(form);
var submit = document.createElement("input");
submit.type = "submit";
form.appendChild(submit)
Var c= document.getElementById("input-a1)
document.write('c'). }
tableCreate();
</script>
</body >
This should work.
<script>
window.onload = function () {
function tableCreate() {
var body = document.body;
var tbl = document.createElement('table');
tbl.style.width = '100px';
tbl.style.border = '2px solid black';
var n = 5;
for (var i = 0; i < n; i++) {
var tr = tbl.insertRow();
var td = tr.insertCell(0);
var tf = tr.insertCell(0);
var input = document.createElement('input');
input.name = "input-a" + i;
input.id = "input-a" + i;
input.value = "test";
var clone = input.cloneNode();
clone.name = "input-b" + i;
clone.id = "input-b" + i;
td.appendChild(clone);
tf.appendChild(input);
td.style.border = '2px solid black';
tf.style.border = '2px solid black';
}
var form = document.createElement("form");
form.appendChild(tbl);
body.appendChild(form);
var submit = document.createElement("input");
submit.type = "submit";
form.appendChild(submit)
var c = document.getElementById("input-a1").value;
document.write(c);
};
tableCreate();
};
</script>
I saw you did document.write('c') with quotes,
this will write the string c and not the variable c.
Also you have to take the value of the input and not the input itself.
var c = document.getElementById("input-a1").value;
code is writing 'c' because you type
document.write('c')
if you want to have value of c you should type
document.write(c.value);
but to have it working you should set this value in function which handles forms submit not after generating form...because now value is empty string
here you have working example
https://jsfiddle.net/g8rschsu/

Change Div Content with JavaScript, onmouseover and onmouseout?

I have the following code:
window.onload = function createDivs() {
for(var i = 1;i<29;i++) {
var div = document.createElement("div");
var body = document.getElementsByTagName("body")[0];
var n1 = document.createTextNode("Cell " + i);
var n2 = document.createTextNode(i + " Cell");
div.style.width = "100px";
div.style.height = "100px";
div.style.border = "1px solid red";
div.style.cssFloat = "left";
div.style.margin = "1px"
div.className = i;
body.appendChild(div);
}
div.onmouseover = function() {
this.appendChild(n1);
},
div.onmouseout = function() {
this.appendChild(n2);
}
}
what I want to acheive
on mouseover of each div, the div should have a text of cell 1, cell 2, ..... upto cel 28. But I am just getting Cell 28 on hover for each cell.
2. I also want to achieve that onmouseout, the cell should have "1 cell" as text, but its not working.
Any help is appreciated.
http://jsbin.com/iXuLEDE/7/edit?html,output
Your problem is coming from your closure over n1 and n2. The simplest solution to that is the following.
From this:
div.onmouseover = function() {
this.appendChild(n1);
}
To this:
div.onmouseover = (function(text) {
return function () {
this.innerHTML = text;
}
}(n1.textContent));
This way you are using a copy of the text node (by using it as a parameter to a function) rather than as a closure later on.
UPDATE
Just read the second part of your question, this should work:
div.onmouseover = (function(text) {
return function() {
this.innerHTML = text;
};
}("Cell " + i));
div.onmouseout = (function(text) {
return function() {
this.innerHTML = text;
};
}(i + " Cell"));
USING TEXT NODES
function createDivs() {
for(var i = 1;i<29;i++) {
var div = document.createElement("div");
var body = document.getElementsByTagName("body")[0];
div.style.width = "100px";
div.style.height = "100px";
div.style.border = "1px solid red";
div.style.cssFloat = "left";
div.style.margin = "1px"
div.className = i;
var n1 = document.createTextNode("Cell " + i);
var n2 = document.createTextNode(i + " Cell");
body.appendChild(div);
div.onmouseover = (function(n_text1, n_text2) {
return function() {
if (n_text2.parentNode == this) {
this.removeChild(n_text2);
}
this.appendChild(n_text1);
};
}(n1, n2));
div.onmouseout = (function(n_text1, n_text2) {
return function() {
if (n_text1.parentNode == this) {
this.removeChild(n_text1);
}
this.appendChild(n_text2);
};
}(n1, n2));
}
}
Fiddle here: http://jsfiddle.net/Mk5e5/
Please change the code like this
window.onload = function createDivs() {
for(var i = 1;i<29;i++) {
var div = document.createElement("div");
div.setAttribute("index", i);
var body = document.getElementsByTagName("body")[0];
div.style.width = "100px";
div.style.height = "100px";
div.style.border = "1px solid red";
div.style.cssFloat = "left";
div.style.margin = "1px"
div.className = i;
body.appendChild(div);
div.onmouseover = function() {
var n1 = document.createTextNode("Cell " + this.getAttribute("index"));
this.appendChild(n1);
} ,
div.onmouseout = function() {
var n2 = document.createTextNode(this.getAttribute("index") + " Cell");
this.appendChild(n2);
}
}
}
You should add event for each div in loop
Try to understand javascript closures, specially inside for loops. Check this excellent explanation in this blog post: http://www.mennovanslooten.nl/blog/post/62
Change your createDivs function to:
function createDivs() {
for(var i = 1;i<29;i++) {
var div = document.createElement("div");
var body = document.getElementsByTagName("body")[0];
div.style.width = "100px";
div.style.height = "100px";
div.style.border = "1px solid red";
div.style.cssFloat = "left";
div.style.margin = "1px"
div.className = i;
body.appendChild(div);
div.onmouseover = (function(value) {
return function() {
var n1 = document.createTextNode("Cell " + value);
this.appendChild(n1);
}
})(i);
div.onmouseout = (function(value) {
return function() {
var n2 = document.createTextNode(value + " Cell");
this.appendChild(n2);
}
})(i);
};
};
Your code doesn't work because when your onmouseover and onmouseout functions are executed, the value of your text variables is "cell 28." Also, your child removal was a little off, if I interpret your intentions correctly.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<script type="text/javascript">
function createDivs(n) {
for(var i = 1; i <= n; i++) {
var div = document.createElement("div");
var body = document.getElementsByTagName("body")[0];
div.style.width = "100px";
div.style.height = "100px";
div.style.border = "1px solid red";
div.style.cssFloat = "left";
div.style.margin = "1px"
div.className = i;
body.appendChild(div);
div.onmouseover = function() {
if (this.childNodes.length > 0) this.removeChild(this.childNodes[0]);
var n_text = document.createTextNode("Cell " + this.className);
this.appendChild(n_text);
},
div.onmouseout = function() {
if (this.childNodes.length > 0) this.removeChild(this.childNodes[0]);
var n_text = document.createTextNode(this.className + " Cell");
this.appendChild(n_text);
}
}
}
createDivs(28)
</script>
</body>
</html>
I also changed your if statement so you pass the number of cells you want instead of the number of cells +1.

Categories