Create divs and add images on the fly - javascript

I'm creating 4 divs and adding 4 images in to each div.
var divid = ["aa","bb","cc","dd"],
imgid = ["a.png","b.png","c.png","d.png"];
for(var i = 0; i < divid.length;i++ ){
document.write('<div id="'+divid[i]+'" class="divCl"><input type="image" src="'+imgid[i]+'" class="imgCl"/></div>');
}
css:-
.divCl{
/*display: none;*/
}
.imgCl{
width: 100px;
height: 100px;
}
Why isn't the css applying? also is it ok to use this method to create divs and add images?

Well, document.write will overwrite the entire contents of the DOM once the document is loaded so you should not use this. You should instead use document.getElementById to select the parent element where you want to insert the images and then set the .innerHTML of that element to the new images. Here is an example:
HTML
<div id="imgParent"></div>
JS
var divid = ["aa","bb","cc","dd"],
imgid = ["a.png","b.png","c.png","d.png"];
var imgs = '';
for(var i = 0; i < divid.length;i++ ){
imgs += '<div id="'+divid[i]+'" class="divCl"><input type="image" src="'+imgid[i]+'" class="imgCl"/></div>';
}
var parent = document.getElementById('imgParent');
parent.innerHTML = imgs;
Output HTML
<div id="imgParent">
<div id="aa">
<input type="image" src="a.png" class="imgCl" />
</div>
<div id="bb>
<input type="image" src="b.png" class="imgCl" />
</div>
...
</div>

There is a syntax error.
Your arrays elements are not strings. The elements are variables not defined. I used jQuery to append each div to the body.
var divid = ['aa','bb','cc','dd'],
imgid = ['a','b','c','d'];
for(var i = 0; i < divid.length; i++ ) {
var str = $('<div id="'+ divid[i] +'" class="divCl"><input type="image" src="'+ imgid[i] +'" class="imgCl"/></div>');
$('body').append(str);
}
https://jsfiddle.net/hjepjnk3/

Going the document.write route will cause your CSS (and everything else) to be overwritten. A better way would be to create a container div and place the new div's in there
var divid = ["aa","bb","cc","dd"],
imgid = ["a.png","b.png","c.png","d.png"];
for(var i = 0; i < divid.length;i++ ){
document.getElementById('containerDiv').innerHTML += '<div id="'+divid[i]+'" class="divCl"><input type="image" src="'+imgid[i]+'" class="imgCl"/></div>'
}
You could also just add it directly to the body by doing
document.getElementsByTagName('body')[0].innerHTML

Related

add div id and for attribute sequentially using js

I want to dynamically add the id and for attribute for each input and label element.
<div id="splash">
<div class="tab">
<input id="tab-1">
<label for="tab-1"><label>
</div>
<div class="tab">
<input id="tab-2">
<label for="tab-2"><label>
</div>
<div class="tab">
<input id="tab-3">
<label for="tab-3"><label>
</div>
</div>
So basically I would want the id for the input to be tab-# with the # increasing by 1 for each input field and the same for the "for=" attribute for the label.
It's super easy. Just iterate through each .tab, using each's index argument, and modify the attributes of the elements.
$('.tab').each(function (index) {
var tabName = 'tab-' + (index + 1);
$('input', this).attr('id', tabName);
$('label', this).attr('for', tabName);
});
Jsbin: http://jsbin.com/rawatag/4/edit?html,js,output
Ok.
I won't give you a straight answer but this should be more useful in future.
Basically make the container <div id=splash>
Then run this command document.getElementById("parentID").innerHTML += "Something here"
This will add the content (pay attention to. The += sign) to the div (splash)
Then, just wrap this in a loop using a counter to get the desired result
Eg: ...innerHTML += "<div id=tab-" + counter + "></div>"
Note that this can be done in raw JS. No JQuery required.
No need for jQuery here:
es5 (jsfiddle)
function assignInputsAndLabels(root) {
var children = root.children;
var tabNumber = 1;
for (var i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', 'tab-' + tabNumber);
children[i].getElementsByTagName('label')[0].setAttribute('for', 'tab-' + tabNumber);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
es6
function assignInputsAndLabels(root) {
const children = root.children;
let tabNumber = 1;
for (let i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', `tab-${tabNumber}`);
children[i].getElementsByTagName('label')[0].setAttribute('for', `tab-${tabNumber}`);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
The parameter to the function is the wrapper of the elements that have the class of tab. In your case, you'd pass in the DOM node of the element with id of splash. So you'd call the function like this:
assignInputsAndLabels(document.getElementById('splash'));
I have done it using javascript.Check it below
function init(){
var sel = document.getElementsByClassName("tab");
var i=1;
for(let obj of sel){
var attr = "tab-"+i;
obj.getElementsByTagName('input')[0].setAttribute("id",attr);
obj.getElementsByTagName('label')[0].setAttribute("for",attr);
i++;
}
}
addEventListener("load",init);
<div class="tab">
<input type="text">
<label></label>
</div>
<div class="tab">
<input type="text">
<label></label>
</div>

How to put a link in a div?

Suppose I have this HTML:
<article id="1919">
<div class="entry-content clearfix">
<div></div>
<div></div>
</div>
</article>
<article id="1910">
<div class="entry-content clearfix">
<div></div>
<div></div>
</div>
</article>
I need to put a link in div with class "entry-content clearfix" for all articles
So can I do it JavaScript:
//take all div with these class value
var eventi_programma=document.getElementsByClassName('entry-content');
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
eventi_programma[i].parentElement.innerHTML=''+eventi_programma[i].outerHTML+'</div>';
}
But my code doesn't work.
(function (){
var eventi_programma=document.getElementsByClassName('entry-content');
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
eventi_programma[i].parentElement.innerHTML=' THIS IS A LINK </div>';
}
})();
It didn't work because you are putting eventi_programma[i].outerHTML as text of the link. As your for loop is based on .entry-content class it basicly creates a never ending for loop since you keep creating new divs with that classname. So instead of putting outerHTML put some other text.
I assume your entry-content class has only one in every article tag ! So I retrieve all article and added then replace it.
var eventi_programma = document.getElementsByTagName("article");
//for to read these elements
for(var i=0;i<eventi_programma.length;i++){
var link="http://www.google.it";//(LINK EXAMPLE);
org_html = eventi_programma[i].innerHTML;
new_html = "<a href='"+link+"'>" + org_html + "</a>";
eventi_programma[i].innerHTML = new_html;
}
//take all div with these class value
var eventi_programma = $('div.entry-content');
//for to read these elements
for (var i = 0; i < eventi_programma.length; i++) {
var link = "http://www.google.it";//(LINK EXAMPLE);
var temp = eventi_programma[i];
$(temp).parent('article').html('</div>')
}
try it...

How could I add the same string on different paragraph multiple time on the same HTML page?

I wish to know the best way to write only once the same thing and repeat inside the same page. For example:
<div>
<p id="description1"></p>
</div>
<div>
<p id="description1"></p>
</div>
--
I wish to write only one time the description1 inside the body. I think this could be achieved using the DOM.
Put the elements in the same class using the class attribute, then get the list of all elements using the getElementsByClassName() DOM function. You can then go over the list using a for loop.
[].forEach.call(document.getElementsByClassName("description"), function(elem) {
elem.innerHTML = "StackOverflow saved my day!";
});
You can even put the text in all elements of the same class using no JavaScript and only CSS by using the content attribute.
First of all, the ID field should be unique per element.
If you give all the tags a class <p class="description"></p> then you can use jQuery to set them all by calling:
$('.description').text('This is the text')
In javascript:
var elements = document.getElementsByClassName("description");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is the text.";
}
Have a look at the solutions proposed here
How to repeat div using jQuery or JavaScript?
this one seems to work pretty well:
html:
<div id="container">data</div>
js:
var container = document.getElementById('container');
function block(mClass, html) {
//extra html you want to store.
return '<div class="' + mClass + '">' + html + '</div>';
}
// code that loops and makes the blocks.
// first part: creates var i
// second: condition, if 'i' is still smaller than three, then loop.
// third part: increment i by 1;
for (var i = 0; i < 3; i++) {
// append the result of function 'block()' to the innerHTML
// of the container.
container.innerHTML += block('block', 'data');
}
JSFIDDLE
Just added with a code by using
getElementsByClassName()
`<html>
<body>
<div class="example">First div element with class="example".</div>
<p class="example">Second paragraph element with class="example".</p>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i=0;i< x.length;i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>`
If you wish to keep id, change your code like this :
script :
var pcount = 2// # p
var desc = document.getElementById('description1');
for(i=0; i<pcount;i++){
document.getElementById('description' + i).innerHTML = desc;
}
html
<div>
<p id="description1"></p>
</div>
<div>
<p id="description2"></p>
</div>
two elements cannot have same id but can have same class
<head>
<script>
var x = document.getElementsByClassName("description");
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = "This is the text.";
}
</script>
<style>
.description1 { // this will apply the same style to all elements having class as description1
text-align: center;
color: red;
}
</style>
</head>
<body>
<div>
<p class="description1"></p>
</div>
<div>
<p class="description1"></p>
</div>
</body>
See the script tag. this solves your problem

how to place a array[i] items in <img src=""> and <a href=""> tags

i have an retrieved array items in the var test,
for example :
var test = img;
Where test[0] holds the value that is grabbed from database as /images/gallery/1.jpp
Now i need to place the var test[0] to be place within img src="" and a href="", so how can i achieve this?
Assign a value to the property "id" of your img and play with its attributes.
<img src="" id="image_id_here" width="300" height="400">
<script>document.getElementById('image_id_here').setAttribute('src', test[0]);</script>
Assumptions made:
"test" is an array of strings
You demand working through a client-sided scripting language such as Javascript to perform front-end operations.
you need a div tag with the id of container:
<div id="container"></div>
You can then use javascript to iterate over the list:
var imgs = "";
for (var i = 0; i < test.length; i++) {
var img = document.createElement('img');
img.setAttribute('src', test[i]);
imgs += img.outerHTML;
}
var container = document.getElementById('container');
container.innerHTML = imgs;
See plunker

Appending ascending images based on the id of parent div

Say I had the following three divs with unique ids on a page
<div id="product-id-001"></div>
<div id="product-id-002"></div>
<div id="product-id-003"></div>
What code would I need to add the following image elements based on the id of the div?
<div id="product-id-001">
<img src="images/product-id-001-1.jpg"></img>
<img src="images/product-id-001-2.jpg"></img>
<img src="images/product-id-001-3.jpg"></img>
</div>
<div id="product-id-002">
<img src="images/product-id-002-1.jpg"></img>
<img src="images/product-id-002-2.jpg"></img>
<img src="images/product-id-002-3.jpg"></img>
</div>
<div id="product-id-003">
<img src="images/product-id-003-1.jpg"></img>
<img src="images/product-id-003-2.jpg"></img>
<img src="images/product-id-003-3.jpg"></img>
</div>
Thanks for any tips.
$('div[id^=product]').each(function(index, elem) {
for(var i = 1; i < 4; i++) {
$('<img>', {
src: '/images/' + elem.id + i
}).appendTo(this);
}
});
Demo: http://www.jsfiddle.net/9S9Av/
(You need Firebug or another DOM inspector to see the result)
From the jQuery docs:
"The .append() method inserts the specified content as the last child of each element in the jQuery collection"
So:
$('#product-id-001").append('<img src="images/product-id-001-1.jpg"></img>');
etc...
// Select all elements with an id beginning with product-id:
var $productContainers = $('[id^=product-id]');
// Loop through the matched elements and append the images:
$productContainers.each(function () {
var $this = $(this),
productId = $this.attr('id'),
numImages = 3,
extension = '.jpg';
// Create and append the images based on the configuration above. Note that this
// assumes that each product have three valid images.
for (var i = 1; i <= numImages; i++)
{
var $image = $('<img alt="" />').attr('src', 'images/'+productId+'-'+i+extension);
$image.appendTo($this);
}
});

Categories

Resources