AppendChild Javascript - javascript

I am trying to append images to a bootstrap column but having no luck, does anyone know what is wrong with my code.
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
document.body.appendChild(row);
}
Any help is appreciated.
Thanks

Sorry, but your code doesn't really make any sense. There are lots of things wrong with it:
Here's what you started with:
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
document.body.appendChild(row);
}
Issues:
You create an <img> DOM object, but don't do anything with it.
You need to pass a DOM object to appendChild() NOT pass a string.
You can't construct a string of HTML by adding img[0] into the string. It simply doesn't work that way at all. You either work entirely in HTML strings or you work in constructed HTML objects or you create an HTML object and then set .innerHTML to a string of HTML. You can't just mix the two the way you are.
I'll take a guess at what you want to do:
for (i = 0; i <= 11; i++) {
var src = "http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i];
var row = document.createElement("div");
row.className = 'row';
row.innerHTML = "<div class='col-md-2'><img src='" + src + "'></div>";
document.body.appendChild(row);
}
This code take the following steps:
Calculate the image src URL.
Create your container div DOM object.
Set the desired className on the container object.
Set the .innerHTML property of the container to the HTML string for the HTML that you want in the container (this will automatically create that set of DOM objects in the container).
Append the container to your document.

Here is an all-javascript solution
var camera = ['http://placehold.it/200x200']
for (i = 0; i <= 0; i++) {
var img = new Image();
img.src = camera[i];
var row = document.createElement('div');
row.className = 'row';
var imgContainer = document.createElement('div');
imgContainer.className = 'col-md-2';
imgContainer.appendChild(img);
row.appendChild(imgContainer);
document.body.appendChild(row);
}
and a jsfiddle demo http://jsfiddle.net/576Tm/1

Related

InnerHTML does not outputs anchor elements but instead outputs current pg url. why?

In the following code, links_container.innerHTML = links; outputs http://localhost/pagination/js-pagination.html# instead of <a href='#'>Page 1</a>.
HTML
<div class="pagination-links"></div>
JS
function createLinks() {
var links_container = document.getElementsByClassName('pagination-links')[0];
for(i=1; i<=5; i++){
var link = document.createElement('a');
var txt = document.createTextNode('Page ' + i + " ");
link.setAttribute("href", "#");
link.appendChild(txt);
links_container.innerHTML = link;
}
}
Can anybuddy explain. why
innerHTML is a string property and thus takes a string as value. Your link is an element object and because of this it's implicitly converted to a string with its toString() method, which does indeed return the URL.
Here are two ways you can fix this:
Both of these solutions require you to clear the container before the for loop by running links_container.innerHTML = ''
Append the element with links_container.appendChild(link)
Use the outerHTML of the element object: links_container.innerHTML += link.outerHTML
The first option is the more appropriate one as it inserts the DOM element you created into the DOM directly. The second option converts your DOM element to a string and then forces the browser to create a new DOM element from that HTML. If there had been any event listeners added to the element they would've been lost.
Instead of setting innerHTML try calling appendChild. The link object is an element not an HTML string.
i.e. try changing:
links_container.innerHTML = links;
to
links_container.appendChild(link);
function createLinks() {
var links_container = document.getElementsByClassName('pagination-links')[0];
// clear out previous html
links_container.innerHTML = "";
for (i = 1; i <= 5; i++) {
var link = document.createElement('a');
var txt = document.createTextNode('Page ' + i + " ");
link.setAttribute("href", "#");
link.appendChild(txt);
// append link to container
links_container.appendChild(link);
}
}
createLinks();
<div class="pagination-links"></div>
Solution using innerHTML:
links_container.innerHTML += link.outerHTML;
or
links_container.innerHTML += "<a href='#'>Page " + i + " </a>"
function createLinks() {
var links_container = document.getElementsByClassName('pagination-links')[0];
// clear out previous html
links_container.innerHTML = "";
for (i = 1; i <= 5; i++) {
var link = document.createElement('a');
var txt = document.createTextNode('Page ' + i + " ");
link.setAttribute("href", "#");
link.appendChild(txt);
// add link
links_container.innerHTML += link.outerHTML;
// or you can use this instead of the above code
//links_container.innerHTML += "<a href='#'>Page " + i + " </a>";
}
}
createLinks();
<div class="pagination-links"></div>
Replace this line
links_container.innerHTML = links;
with
links_container.innerHTML = link;
as you do not have any links variable there.

For loop exceeds the limit when using img src

I have an img_urls array which contains 2 image urls.
I use this array to loop img tag and using for loop.
But instead of having 2 images, i have 3 images in my output.
This is my code;
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
So, whats is wrong with my code?
JSFIDDLE
When adding the first image you generate a new div.
Then the second image if appended to existing divs.
You should have only one destination div. Add an id to the main div:
<div id="container"></div>
--
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
You need to use selector i.e. id class in the main div as when the next iteration occurs it contains two div in the body. Check this fiddle
Problem is that you have $("div") as selector. So when you append the first image, you also add new div. So the next image is appended to two divs. Probably you can add id to your div, so
<div id="test"></div>
...
$("#test").append
Reason is you are appending everything inside the loop.
$(function() {
var img_urls = ["url1", "url2"];
var html= ""
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>";
}
$("div").append(html);
});
You are appending to global div element, you are appending div also, so generated html will append to generated div too.
Here is html,
<div class='test'></div>
Here is javascript code,
$(function() {
var img_urls = ["image_url1", "image_url2"];
var html = '';
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>"
}
$("div.test").append(html);
});
Please find here working link here
I hope this will help
<div id="container"></div>
for (var i = 0; i < img_urls.length; i++) {
console.log(img_urls.length)
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
when you append the first image you create a div in that div the horse is added and the first div is also populated by the horse
Try this and see Demo
<div></div>
$(function() {
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<img src=' " + img_urls[i] + "'/> </br>"
);
}
});

How to handle quoting of HTML in JavaScript document.write

I'm using document.write to take an array of images and I want to add an onclick event handler to each image by looping through this array. I'm having a very hard time figuring out where to put quotes in this JavaScript code:
for (index = 0; index < buildings.length; index++) {
document.write(
"<img onclick='" + setPhoto() +
"' id='" + images[index].id +
"' src='" + images[index].src +
"' width='50' height='50'/>"
);
};
All help is appreciated.
Pretty much no one uses document.write anymore. Read the disclaimer in the docs
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
You're better off doing something like this
for (var index = 0, img; index < buildings.length; index++) {
img = document.createElement('img');
img.src = images[index].src;
img.width = 50;
img.height = 50;
img.onclick = setPhoto;
document.body.appendChild(img);
}
This will attach the images to document.body but you could attach them to any other element you wanted

Using javascript for statement to create a bunch of thumbnail picture links

I want to use javascript to fill a section of a HTML page with thumbnail images that link to the full sized imagaes. Currently all that happens when this code runs is it prints the p open and close. I want it do make the thumbnails for img (#) where # is 1-41.
javascript:
document.getElementById('img').innerHTML = "<p>"
for( var img = 1; img >= 41; img++)
{
document.getElementById('img').innerHTML += ("<a href='img/pic (" + img + ").JPG'><img src='img/thumbs/pic (" + img + ").png' width=156 height=84 alt='img " + img + "'></a>")
}
document.getElementById('img').innerHTML += "</p>"
HTML:
<div class="main">
<div id="img"><div>
</div>
Two things:
Both inside the loop and after it, you're assigning a completely new value to the innerHTML of the element, overwriting anything you might have had in it before. Apparently after the initial post, you edited the question to use += instead. Even so, using innerHTML += ... is a bad idea, as it causes the browser to constantly re-serialize the DOM of the element and re-parse the string each time, and if you hand it half-complete HTML (such as "<p>"), what it uses when you do += may well be "<p></p>" — and so when you add to it, what you add ends up in the wrong place. Instead, build up the text in a variable and then assign it once, at the end.
You're starting with img = 1 and then telling the loop to continue while img >= 41. So the loop body is never run, since 1 is not >= 41.
Minimal update:
var markup = "<p>";
for( var img = 1; img <= 41; img++)
{
markup += "<a href='img/pic (" + img + ").JPG'><img src='img/thumbs/pic (" + img + ").png' width=156 height=84 alt='img " + img + "'></a>";
}
document.getElementById('img').innerHTML = markup + "</p>";
You have an error in for condition section. Replace
for( var img = 1; img >= 41; img++)
with
for( var img = 1; img <= 41; img++)

Changing the content of all <pre> tags using JavaScript

I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}

Categories