Looping through a set of <p>'s one at a time - javascript

I'm trying to figure out how to count the number of p's so every time the button is pressed, it outputs to 0 to 1 until the maximum number of p's is counted.
var big_number = 999999;
var i;
var a = document.getElementsByTagName("p");
function function0() {
for (i=0; i < big_number; i++) {
document.getElementsByTagName("p")[i].innerHTML="text";
}
}
I want it to write to another p every time the button is pressed.

document.getElementsByTagName("p").length // number of p elements on the page
Is that what you were asking?

Make a generic tag adder function then call it:
function addTags(tagName,start, max, container) {
var i = start;
for (i; i < max; i++) {
var newp = document.createElement(tagName);
newp.innerHTML = "paragraph" + i;
container.appendChild(newp);
}
}
var tag = 'p';
var big_number = 30;
var i;
var a = document.getElementsByTagName(tag );
// **THIS is your specific question answer**:
var pCount = a.length;
var parent = document.getElementById('mydiv');
addTags(tag,pCount , big_number, parent);
// add 10 more
a = document.getElementsByTagName(tag );
pCount = a.length;
big_number = big_number+10;
addTags(tag,pCount , big_number, parent);
EDIT:
NOTE: THIS might be better, only hitting the DOM once, up to you to determine need:
function addTagGroup(tagName, start, max, container) {
var tempContainer = document.createDocumentFragment();
var i = start;
for (i; i < max; i++) {
var el = document.createElement(tagName);
el.textContent = "Paragraph" + i;
tempContainer.appendChild(el);
}
container.appendChild(tempContainer);
}

To find out how many <p> elements there are in the document you should use DOM's length property as below :-
var numP = document.getElementsByTagName("P").length;
or
var div = document.getElementById("myDIV");
var numP = div.getElementsByTagName("P").length;
To get number of element inside a tag.

Related

Why can't I get my images to appear in table cells/nodes.. maybe I can get some closure?

I want to add a new image in each cell of the new table and give it the same source as the old table, and then make it clickable. Firstly, I did this:
function showData() {
if (localStorage.getItem(name) !== null) {
var showme = localStorage.getItem(name);
alert("I got the table");
var newTable = document.createElement('table');
newTable.innerHTML = showme;
newTable.id = "newTable";
newNumRows = newTable.getElementsByTagName('tr').length;
newNumCells = newTable.getElementsByTagName('td').length;
newNumCols = newNumCells / newNumRows;
alert(newNumRows);
alert(newNumCells);
alert(newNumCols);
var newImages = newTable.getElementsByTagName('img');
for (var i = 0; i < newImages.length; i += 1) {
var picSource = newImages[i]['src'];
console.log(picSource);
}
function addNewImage(newNumCols) {
var newImg = new Image();
newImg.src = picSource;
col.appendChild(newImg);
newImg.onclick = function() {
alert("WOW");
};
}
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
col = row.insertCell(-1);
addNewImage(newNumCols);
}
}
var showIt = document.getElementById('holdTable');
showIt.appendChild(newTable);
}
}
This works to a certain extent, but, unfortunately, only the last image was displaying. So, I did a bit of looking around and I think it has to do with closure (apologies for any duplication), but it's a concept I am really struggling to understand. So then I tried this:
function showData() {
if (localStorage.getItem(name) !== null) {
hideTaskForm();
var showme = localStorage.getItem(name);
var oldTable = document.createElement('table');
oldTable.innerHTML = showme;
newTable = document.createElement('table');
newTable.id = "newTable";
var i, r, c, j;
newNumRows = oldTable.getElementsByTagName('tr').length;
newNumCells = oldTable.getElementsByTagName('td').length;
newNumCols = newNumCells / newNumRows;
var newTableCells = newTable.getElementsByTagName('td');
var getImages = oldTable.getElementsByTagName('img');
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
makeNodes = row.insertCell(-1);
}
}
for (var j = 0; j < newTableCells.length; j++) {
var theNodeImage = document.createElement("img");
newTableCells[j].appendChild(theNodeImage);
alert(newTableCells[j].innerHTML); //This gives me img tags
}
for (i = 0; i < getImages.length; i += 1) {
var oldSource = getImages[i]['src']; //gets the src of the images from the saved table
console.log(oldSource);
//alert(oldSource);//successfully alerts the image paths
var newPic = new Image(); //creates a new image
(function(newPic, oldSource) {
newPic.src = oldSource;
alert(newPic.src); //gives the same image paths
newTable.getElementsByTagName('img').src = newPic.src; //This doesn't work - table is blank???
})(newPic, oldSource);
}
var showIt = document.getElementById('holdTable');
showIt.appendChild(newTable);
}
}
Now, this doesn't throw any errors. However, nor does it fill the table. It does give me the source and I think I have created the new image objects to attach to the img tags in the newTableCells, but the table is showing up blank. I don't know where I am going wrong. All help really welcome.
Note: Even as a hobbyist, even I know there are probably tons of more efficient ways to do this, but I purposely did it this way to try and help me understand the logic of each step I was taking.
In your code you have:
var newImages = newTable.getElementsByTagName('img');
for (var i = 0; i < newImages.length; i += 1) {
var picSource = newImages[i]['src'];
console.log(picSource);
}
At the end of this, picSource has the value of the last image's src attribute. Then there is:
function addNewImage(newNumCols) {
var newImg = new Image();
newImg.src = picSource;
col.appendChild(newImg);
newImg.onclick = function() {
alert("WOW");
};
}
A value is passed to newNumCols but not used in the function. The value of picSource comes from the outer execution context and is not changed, so it's still the last image src from the previous for loop.
for (r = 0; r < newNumRows; r++) {
row = newTable.insertRow(-1);
for (c = 0; c < newNumCols; c++) {
col = row.insertCell(-1);
addNewImage(newNumCols);
}
}
This loop just keeps calling addNewImage with a single parameter that isn't used in the function, so you get the same image over and over.
For the record, the addNewImage function does have a closure to picSource, but it also has a closure to all the variables of the outer execution contexts. This isn't the issue, though it perhaps masks the fact that you aren't setting a value for picSource on each call, so you get the left over value from the previous section of code.
You haven't provided any indication of the content of showme, so it's impossible to determine if this approach will work at all.
Note
Where you have:
var showme = localStorage.getItem(name);
alert("I got the table");
var newTable = document.createElement('table');
newTable.innerHTML = showme;
newTable.id = "newTable";
IE does not support setting the innerHTML property of table elements, though you can create an entire table as the innerHTML of some other element and set the innerHTML of a cell (tr, th). If you want to use this approach, consider:
var div = document.createElement('div');
div.innerHTML = '<table id="newTable">' + showme + '<\/table>';
var newTable = div.firstChild;

how to create more elements for the entered value in a textboxes in javascript?

I use for loop to create 3 textboxes with it's ids in javascript.. if I enter numbers on each text box I want to display same number of paragraphs element under each text box..
I have a problem: each textbox affected when i enter value in the other text boxes..
There is my codes:
for (i = 0; i < 3; i++) {
var tx = document.createElement('input');
tx.setAttribute('id', i);
tx.onblur = function () {
for (i = 0; i < 3; i++) {
var no = document.getElementById(i).value;
num = Number(no);
var d = document.getElementById('di' + i);
for (x = 0; x < num; x++) {
var tx1 = document.createElement('p');
tx1.innerHTML = " p" + x;
d.appendChild(tx1);
}
}
};
var div1 = document.createElement('div');
div1.setAttribute('id', "di" + i);
var div = document.getElementById('div1');
div.appendChild(tx);
div.appendChild(div1);
}
There are issues in code.
1)
var div = document.getElementById('div1');
div.appendChild(tx);
The code is asking for div with ID div1 which is never appended to DOM hence it returns null
thus null.appendChild(tx) fails.
Thanks
Added JSFiddle. If this is what you are trying to make..
http://jsfiddle.net/khm63wte/
just change your code, create a div on your document <div id="t"></div>, in your javascript create div first, then your input and append them to the document here is a working code
for (i = 0; i < 3; i++) {
var div1 = document.createElement('div');
div1.setAttribute('id', "di" + i);
document.getElementById('t').appendChild(div1)
var tx = document.createElement('input');
tx.setAttribute('id', i);
document.getElementById("di"+i).appendChild(tx);
tx.onblur = function () {
for (i = 0; i < 3; i++) {
var no = document.getElementById(i).value;
num = Number(no);
var d = document.getElementById('di' + i);
for (x = 0; x < num; x++) {
var tx1 = document.createElement('p');
tx1.innerHTML = " p" + x;
d.appendChild(tx1);
}
}
};
}

How to add spans to every word in paragraph of text?

How to append a span to every word in a particular document div ("text")? New to using nodes in js. Keep getting message,
"object has no method append child..."
What am I missing? This is my code:
var y;
var words;
function get() {
y = document.getElementById("text").firstChild.nodeValue;
words = y.split(" ");
for (var x = 0; x < 3; x++)
{
var newSpan = document.createElement('span');
words[x].appendChild(newSpan);
}
}
You need to first fetch the dom element you want to append the words to,
elem = documents.getElementById("#some_container");
Then append the words to it
words.forEach(function(w) {
var new_span = document.createElement('<span>');
new_span.innerHTML = w;
elem.appendChild(new_span);
});

Get the source of images from table cell

I am trying to get to the img.src of these table cells, but am going wrong somewhere.
var cell = newTable.rows.cells;
var content = newTable.getElementsByTagName('img');
var nodeArray = [];
for(var i = 0; i < content.length; ++i)
{
nodeArray[i] = content[i];
}
var listThem = $(this).attr('src');
console.log(listThem);
Use this :
var content = newTable.getElementsByTagName('img');
for(var i = 0; i < content.length; i += 1) {
var source = content[i]['src'];
//do something
}
getElementsByTagName() returns an array of dom elements.
To access the "src" attribute of a dom element, you can do this : element.src or element['src'];
source will contain the image source.

How to add DOM Element in for loop

How can I create new Element each time when (i) will be incremented:
for(int i = 0; i < 10; i++)
{
Element child = doc.createElement("xxx");
root.setAttribute("x", i * "xx");
doc.appendChild(child);
}
Using pure js
var div = document.getElementById("main");
for (var i = 0; i < 10; i++) {
var span = document.createElement("span");
span.setAttribute("class", "new");
span.innerHTML = "span" + i;
div.appendChild(span);
}​
HTML
​<div id="main"></div>​​​​​​​
Working example.
Cheers!!
Using java
Element child = null;
for(int i = 0; i < 10; i++)
{
child = doc.createElement("xxx" + i);//you can write a method with int parameter to get element name from somewhere else
doc.appendChild(child);
}
I hope this is what you wanted, by the way for text nodes you should use doc.createTextNode("A")

Categories

Resources