Get the source of images from table cell - javascript

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.

Related

Replace all img src on page load - Javascript

I'm trying to replace all img src's on my page, when they have a certain url in them. So far I'm able to log all the replaced img src's, but my final step would be to change them on my page.
function replaceMyImgs() {
// put live url here
var liveUrl = "via.placeholder.com";
// find the local url
var localUrl = "testdomain.com";
// replace the local url for the live url
var newUrl = localUrl.replace(/testdomain.com/g, liveUrl);
// console.log(newUrl);
// get all images and push them in an empty array
var imgs = document.getElementsByTagName("img");
var imgSrcs = [];
for (var i = 0; i < imgs.length; i++) {
imgSrcs.push(imgs[i].src);
}
imgSrcs.forEach(function(src) {
// log all the found img srcs
var newSrc = src.replace(/testdomain.com/g, liveUrl);
imgs.src = newSrc;
console.log(imgs.src);
});
}
window.onload = replaceMyImgs;
See my pen: https://codepen.io/kleefaan/pen/yqzBVv
Instead of pushing all elements into an array you can do the replace in the for loop like this:
// get all images
var imgs = document.getElementsByTagName("img");
for (var i = 0; i < imgs.length; i++) {
var newSrc = imgs[i].src.replace(/testdomain.com/g, liveUrl);
imgs[i].src = newSrc;
console.log(imgs[i].src);
}

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

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.

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 can I change the content of the "h1" tag of an html page using javascript?

I need to change the content of all "h1" tags in my html file when the page load using javascript.
So I write the following code
window.onload = function () {
var h1html = document.createElement("h1");
var h1htmltext = document.createTextNode("header 1");
h1html.appendChild(h1htmltext);
document.getElementsByTagName("h1").appendChild(h1html);
};
If you're sure you only have one h1 tag you could simply do
window.onload = function () {
document.getElementsByTagName("h1")[0].innerHTML = "header 1";
}
if multiple h1 tags are present you could do
window.onload = function () {
var h1Elems = document.getElementsByTagName("h1");
var pos;
for (pos in h1Elems) {
h1Elems[pos].innerHTML = "header 1";
}
}
Use this:
for(var i = 0, elems = document.getElementsByTagName('h1'); i < elems.length; i++) {
elems[i].innerHTML = "new";
}
fiddle
You need to change the innerHTML of each elements, as such
function changeall(){
var headers=document.getElementsByTagName("h1");
var newheadertext="hello";
for(var i in headers){
headers[i].innerHTML=newheadertext;
}
}
getElementsByTagName returns a node list; you need to loop through it.
var headers = document.getElementsByTagName("h1");
for(var i = 0; i < headers.length; i++) {
var header = headers[i];
var text = document.createTextNode("header 1");
while(header.childNodes.length) {
header.removeChild(header.firstChild);
}
header.appendChild(text);
}
I made a few assumptions there:
You don’t actually want to nest headers
You want to replace the content
You want an old-standards-compliant way
If you don’t need support for old browsers, just use textContent:
var headers = document.getElementsByTagName("h1");
for(var i = 0; i < headers.length; i++) {
headers[i].textContent = "header 1";
}

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