This is a really simple question but I don't know why it doesn't work. I have an array with 4 items inside. And I have a container which I would like to insert a number of divs based on the number of items in my array. I used a for loop for this but it is only creating one div. Should it not create 4 of the same div elements?
This is the code:
count = new Array['1', '2', '3', '4'];
container = document.getElementById('items');
for (i = 0; i < count.length; i++) {
container.innerHTML += '<div id="items"></div>';
}
#items {
width: 20px;
height: 20px;
background: gold;
}
<div id="items"></div>
This is the link http://codepen.io/2bu/pen/jyxNbw
The way you are creating the array is incorrect.
Try this instead:
var count = ['1', '2', '3', '4'];
Note: Inside the for loop, you are creating elements that have the same ID. IDs should be unique.
Also, as mentioned you will want to append to the 'items' div instead of adding a new div with a duplicate id.
I would do something like this:
var count = ['1','2','3','4'];
var container = document.getElementById('items');
for(var i = 0; i < count.length; i++){
container.append('<div>' + count[i] + '</div>');
}
And to improve the iteration:
var counts = ['1','2','3','4'];
var container = document.getElementById('items');
counts.forEach(function(count) {
container.append('<div>' + count + '</div>');
});
It is rarely necessary to use for(var i = 0; i < x; i++). Using forEach, map or reduce are considerably better (code is more concise, temporary variables are unnecessary etc.).
1)You cannot create more DOM elements with same id.Use classes instead.
2)You have to define the array in the following way: var count = ['1', '2', '3', '4'];
Here is the final code:
// var container = document.getElementById("container");
// for (var i = 0; i < array.length; i++) {
// container.innerHTML += '<div class="box"></div>';
// }
count = ['1','2','3','4'];
container = document.getElementById('itemsContainer');
for(i = 0; i < count.length; i++){
container.innerHTML+='<div class="items"></div>';
}
var square= document.getElementsByClassName('items')[2];
square.style.backgroundColor='red';
.items{
margin-top:10px;
width:20px;
height:20px;
background:gold;
}
<div id="itemsContainer"></div>
If you want to access one items DOM element, you have to use document.getElementsByClassName() method which returns a NodeList.
var square= document.getElementsByClassName('items')[2];
square.style.backgroundColor='red';
Related
Hello is it possible to change div tags to image tags?
I tried using this
var testDivTags= document.getElementsByClassName('div_tags');
var testImgTag= document.createElement("img");
for (var i = 0; i < testDivTags.length; ++i) {
testDivTags[i].parentNode.replaceChild(testImgTag, testDivTags[i])
}
But it doesn't work. Any ideas?
The problem is that an element can't be at different places in the DOM simultaneously.
Instead, you should clone the element, and insert the clones:
parent.replaceChild(newChild.cloneNode(), oldChild)
Moreover, there is another problem: the HTMLCollection returned by getElementsByClassName is live. Therefore, when you replace the elements, they disappear from the list, and following ones are reindexed to lower indices. To fix that, you can
Iterate the live HTMLCollection collection backwards:
var liveC = document.getElementsByClassName('div_tags');
for (var i = liveC.length-1; i >= 0; --i)
liveC[i].parentNode.replaceChild(testImgTag.cloneNode(), liveC[i]);
Convert it to an array:
var array = [].slice.call(document.getElementsByClassName('div_tags'));
for (var i = 0; i < array.length; ++i)
array[i].parentNode.replaceChild(testImgTag.cloneNode(), array[i]);
Use querySelectorAll, which returns a static NodeList collection:
var staticC = document.querySelectorAll('.div_tags');
for (var i = 0; i < staticC.length; ++i)
staticC[i].parentNode.replaceChild(testImgTag.cloneNode(), staticC[i]);
I have an array of objects in javascript (D3) and I need to remove every object of which a certain attribute is present in another array of objects attribute,
i.e. a left outer join
(source: tazindeed.co.uk)
I managed to do it myself with 2 loops but it's quite slow.
And I don't know how to make it faster.
for (var i = 0; i < data1.length; i++) {
for (var j = 0; j < data2.length; j++) {
if (data2[j].attr3 == data1[i].attr4) {
data2.splice(j,1);
}
}
}
data1.length~2k and data2.length~10k
I know this has approximately been asked here but it's been almost 2 years and the solutions use external libraries.
I'm just curious to learn if there is a better method with javascript (or jQuery or D3, which I already use)
Thank you for your help !
You need a fast lookup for the values that exist in data1, so make a map using an object:
var map = {};
for (var i = 0; i < data1.length; i++) {
map[data1[i].attr4] = 1;
}
Then you can loop throught the items in data2 and filter them:
var result = [];
for (i = 0; i < data2.length; i++) {
if (!(data2[i].attr3 in map)) {
result.push(data2[i]);
}
}
Maybe not faster but more readable
const left = ['1', '2', '7']
const right = ['1', '3', '5', '9']
const result = left.filter((x) => !right.includes(x))
You could use Array.filter (see MDN) or Array.map for that I suppose:
var array1 = [1,2,3,4,5,6,7,8,9],
array2 = [3,4,5,6],
fltr = array1.filter( function(v) {return this.indexOf(v) < 0;}, array2),
map = array1.map(
function(v) {
var exists = this.indexOf(v);
return [v, (this[exists] || 'null')].join(', ');},
array2),
result = document.querySelector('#result');
fltr.unshift('<u>array1</u>');
map.unshift('<u>array1, array2</u>');
result.innerHTML = ['<b>filtered</b>\n',
fltr.join('\n'),
'\n\n<b>mapped</b>\n',
map.join('\n')].join('');
<pre id="result"></pre>
Creating static variables is not an option in this case becouse it would take to long time and ineffective to what im trying to accomplish. I have an Array with images and I'm trying to create a way to make divs according to the length of the array. 1,2,3,4 etc.
var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;
Which will result in an array length of 3. I would like to create 3 variables for this.
for (var i = 0; i > totalimages; i++){
var div[i] = document.createElement('div');
}
This seems not to be working for some reason. I tried to create a div array/list outside the for loop aswell.
var div = [];
for (var i = 0; i > totalimages; i++){
var div[i] = document.createElement('div');
}
Still not working. I dunno why this is not working. Javascript only
EDIT: (not working) i mean it gives me syntax error.
You have defined div already. In loop you shouldn't be saying like var div again.
BTW var div[ will cause a syntax error.
Use this
div[i] = document.createElement('div');
instead of
var div[i] = document.createElement('div');
Any way I'll prefer saying this at that place
div.push(document.createElement('div'));
And this will cause i > totalimages an infinitive loop, say i < totalimages instead.
i < totalimages
not
i > totalimages
Make sure you don't use var inside the array if you're assigning new values:
var div = [];
for (var i = 0; i < totalimages; i++){
div[i] = document.createElement('div');
}
DEMO
In short:
var images = ['image1.JPG', 'image2.JPG', 'image3.JPG'];
var totalimages = images.length;
var div = [];
for (var i = 0; i < totalimages; i++){
div.push(document.createElement('div'));
}
How can I remove one NodeList from another? For example, if I have:
var all = document.querySelectorAll('*');
var divs = document.querySelectorAll('div');
var removed = all - divs;
This doesn't work however. What is the correct method for doing this with the result being a nodelist and not an array?
You can turn the all nodeList into an array and then use array methods to do searching and removals:
var all = Array.prototype.slice.call(document.querySelectorAll('*'), 0);
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
var pos = all.indexOf(divs[i]);
if (pos !== -1) {
all.splice(pos, 1);
}
}
This requires IE9 (for .indexOf()) or you can use a polyfill to make it work in older versions of IE or you can make your own function that iterates through an array to find if an element matches.
On second thought, there's a bit of an easier way to do this:
var all = Array.prototype.slice.call(document.querySelectorAll('*'), 0);
for (var i = all.length - 1; i >= 0; i--) {
if (all[i].tagName === "DIV") {
all.splice(i, 1);
}
}
var all = document.querySelectorAll('*');
var divs = document.querySelectorAll('div');
var removed = all.filter(function(i){
return divs.indexOf(i) < 0;
});
I want to remove all elements (suppose they're all divs) whose id name contains the string bs. How to do this via javascript regardless of they are nested elements or not? (not jquery)
<div id="new_bs_add"></div>
<div id="bsremove"></div>
<div id="somethingelse"></div>
... and many more
No jQuery, but if there's support for CSS3 selectors you can go for
var rem = document.querySelectorAll("[id*='bs']"), i = 0;
for (; i < rem.length; i++)
rem[i].parentNode.removeChild(rem[i]);
Otherwise, just go for this slight edit of VisioN's solution:
var divs = document.querySelectorAll("[id]");
for (var i = 0, len = divs.length; i < len; i++) {
var div = divs[i];
if (div.id.indexOf("bs") > -1) {
div.parentNode.removeChild(div);
}
}
Pure JavaScript:
var divs = document.getElementsByTagName("div");
for (var i = divs.length; i;) {
var div = divs[--i];
if (div.id.indexOf("bs") > -1) {
div.parentNode.removeChild(div);
}
}
As an example, in jQuery it is one line:
$("div[id*='bs']").remove();
DEMO: http://jsfiddle.net/c4ewU/
The most portable method to obtain a list of elements is document.getElementsByTagName. However the resulting list is a live node list which means that if you modify the document, the list changes too!
There are two solutions for this. One is to take a copy of the list:
var nodes = document.getElementsByTagName('div');
var copy = [].slice.call(nodes, 0); // take a copy
for (var i = 0, n = copy.length; i < n; ++i) {
var d = copy[i];
if (d.parentNode && d.id.indexOf('bs') >= 0) {
d.parentNode.removeChild(d);
}
}
The second is to either work through the list backwards, or ensure that you don't advance the iterator if you modify the list. This takes the latter approach:
var nodes = document.getElementsByTagName('div');
for (var i = 0; i < nodes.length; /* blank */ ) {
var d = nodes[i];
if (d.id.indexOf('bs') >= 0) {
d.parentNode.removeChild(d);
} else {
++i; // iterate forward
}
}
try this code
first get all elements contain certain text (here 'bs')
var matches = [];
var searchElements = document.getElementsByTagName("body")[0].children;
for(var i = 0; i < searchElements.length; i++) {
if(searchElements[i].tagName == 'DIV') {
if(searchElements[i].id.indexOf('bs') != -1) {
matches.push(searchElements[i]);
}
}
}
Then delete them from body of html
for(var i = 0;i<matches.length; i++)
matches[i].parentNode.removeChild(matches[i]);
If you remove them in the first loop, there will be some tags will not deleted as the children array length is decreased each time you delete a node. So the better way to get them all in an external array and then delete them.