GetElementByTagName[ 0 ].setAttribute inside a loop - javascript

I just curious about this.
I created an function that add ID value to a dynamically create li tag.
the function looks like this.
function limenu(lix,liy){
document.getElementsByTagName("li")[0].setAttribute("id",lix);
document.getElementsByTagName("li")[1].setAttribute("id",liy);
} limenu("icon-dice","icon-clock");
My thought is, can I use an for-loop? that let me insert how many events I want without need to create document.getElementsByTagName("li")[1]-[2]-[3].. etc
so when i call the function liemenu(), I would be able to add as many events i want.
I could use Jquery but i really want to do this with Javascript.
Thanks

function limenu() {
var lis = document.getElementsByTagName("li");
var count = Math.min(lis.length, arguments.length);
for (var x = 0; x < count; x++) {
lis[x].setAttribute('id', arguments[x]);
}
}
http://jsfiddle.net/ExplosionPIlls/72hdS/

Related

How to map within a for loop

We need to map an object array within a for loop, which actually works, but the editor is giving us a warning saying not to put a function within a loop:
for(var i=0; i<$scope.data.list.length; i++){
$scope.data.list[i].isRowSelected=false;
var pos1 = $scope.selectedItems.map(function(e) { return e.sys_id; }).indexOf($scope.data.list[i].sys_id);
if(pos1!==-1){
var add = $scope.selectedItems.indexOf($scope.data.list[i].sys_id);
$scope.selectedItems.splice(add,1);
}
}
To mitigate this, we're thinking about creating a separate function for the mapping and then calling it within the loop, like this:
function mappingID(e){
return e.sys_id;
}
However, when we call upon it within the loop, we're lost as to what to pass in...any suggestions? Thanks!
two things, create a function outside the loop and avoid repeating indexing and object nesting. It will make your code much cleaner and easier to reason about. I'm pretty sure this whole function could be done a lot better but I'm not sure of the bigger scope
var items = $scope.selectedItems;
var sys_id = function(e) { return e.sys_id; }
for(var i=0; i<$scope.data.list.length; i++){
var data = $scope.data.list[i]; // might be a better name for this...
data.isRowSelected=false;
var pos1 = items.map(sys_id).indexOf(data.sys_id);
if(pos1!==-1){
var add = items.indexOf(data.sys_id);
items.splice(add,1);
}
}
The comments suggest lodash, which is a good suggestion. For the purposes of your original question, however, you can declare the function mappingID as you have it, and simply put
var pos1 = $scope.selectedItems.map(mappingID).indexOf($scope.data.list[i].sys_id);
and that will do the job.
You don't need to bring lodash to handle this, you can use find: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
for(var i=0; i<$scope.data.list.length; i++){
$scope.data.list[i].isRowSelected=false;
var item = $scope.selectedItems.find(e => (e.sys_id === $scope.data.list[i].sys_id));
if (item) {
$scope.selectedItems.splice(item,1);
}
}
Also I suggest changing selectedItems to an plain-object/Map/Set so you can lookup in constant time.
To avoid doing the same mapping on each iteration of the loop, move the mapping outside the loop:
var idArr = $scope.selectedItems.map(function(e) { return e.sys_id; })
$scope.data.list.forEach(item => {
item.isRowSelected=false;
var pos1 = idArr.indexOf(item.sys_id);
if(pos1!==-1){
var add = $scope.selectedItems.indexOf(item.sys_id);
$scope.selectedItems.splice(add,1);
}
})

Jquery .clone() method. Removing clones

I noticed some interesting behavior when dealing with the .clone() function.
If I have a function to create rows and columns dynamically like this:
function appendDiv(n) {
for (var i=0;i<n;i++) {
$rows.append($columns.clone()); //assume I put $('.rows') & others in a var
}
for (var i=0;i<n;i++) {
$wrapper.append($rows.clone());
}
}
And I then delete the elements from the DOM maybe like this:
function deleteClones() {
$wrapper.off();
$wrapper.html('');
$('body').append($wrapper);
num = prompt("Enter another number.");
return num;
}
So I'd be calling the functions in an order like this:
appendDiv(num);
num = deleteClones();
appendDiv(num);
Can someone tell me why when I call appendDiv(num); again after removing those elements, the old columns are added along with the new ones? Here is a preschool level demonstration of what I mean: http://jsfiddle.net/wj6sgeeu/. Notice upon inspecting the html document, the clones that were created before we called deleteClones() are added again when we call appendDiv(num) for the second time.
I'm new to jquery, so maybe this is a self evident and obvious fact (maybe using a different method to remove clones?) but does someone have an explanation for this behavior?
Thank you!
You need to remove the previously added columns from the row, else you are just keep adding more columns to the existing columns
function appendDiv(n) {
$rows.empty();
for (var i = 0; i < n; i++) {
$rows.append($columns.clone());
console.log('ok');
}
for (var i = 0; i < n; i++) {
$wrapper.append($rows.clone());
console.log('ok2');
}
}
Demo: Fiddle

Multiply an element by a number and insert using jQuery

I'm wondering if you can multiply an element using jQuery a number of times and insert it using .html()?
I am building my own slider which might help put things in context...
I am getting a number of times an element is used, which is stored in a var called eachSlideCount. So for example, this might output 10.
Then what I want to do is create a <span></span> for each of these (so 10 spans) and insert this into a div to generate a pager.
$this.next('.project-slider-count').html('<span></span>')
Is there anyway to muliply this span by the eachSlideCount number and then add to the .project-slider-count element?
I got this far... but clearly missing something...
var eachSlideCount = $this.find('.other-slides').length;
var eachSlideTotal = ($this.next('.project-slider-count').html('<span></span>')) * eachSlideCount;
$('.project-slider-count').html(eachSlideTotal);
Thanks in advance
Multiplication can only be done on numbers. If you want to repeat something, write a loop:
var span = '';
for (var i = 0; i < eachSlideCount; i++) {
span += '<span></span>';
}
$this.next('.projectslider-count').html(span);
In JavaScript, you can execute a for loop. For example, in the following:
var count = 10;
for (var i=0; i<count; i++) {
// Code
}
The body of the loop would be executed 10 times.
In jQuery, you can append a new HTML element inside an existing element using the append() method. For example, the following will add <span> elements in a loop:
var container = $("#container");
var count = 10;
for (var i=0; i<count; i++) {
container.append("<span>");
}
This is illustrated in a jsFiddle.

Get all files for all .uploadedFiles

Im looking for a javascript/jquery (doesn't matter which way) to collect all the files i've uploaded.
I have the following code, where .afbeelding is the class for a couple of file input fields
var geuploadeAfbeeldingen = $('.afbeeldingen').files;
for (var i = 0; i < geuploadeAfbeeldingen.length; i++) {
}
This somehow doesnt seem to work. When i try document.getElementsByClassName it also doesn't work. The funny thing however is, that document.getElementById seem to work on one input field
Any ideas?
This should do what you want
var files = [],
geuploadeAfbeeldingen = $('.afbeeldingen').each(function(){
for (var i = 0; i < this.files.length; i++){
files.push(this.files[i]);
}
});
You end up with an array (files) that holds each file you have selected through the input elements..
Demo at http://jsfiddle.net/gaby/GJW7Y/1/
If you only want the filenames then change
files.push(this.files[i]);
with
files.push(this.files[i].name);
Try this way :
var geuploadeAfbeeldingen = $('.afbeeldingen');
for (var i = 0; i < geuploadeAfbeeldingen.length; i++) {
alert(geuploadeAfbeeldingen[i].files[0].name);
}
This may help you.
Edit :
$('.afbeeldingen').files is not work and document.getElementById().files is worked because first one return JQuery object( array of objects) and second one return DOM object.The jQuery object (created by the $ method) is a wrapper around a DOM element or a set of DOM elements. The normal properties and methods are not available with JQuery object.
You need to loop through each input element and return the files property.
Something like this is probably the shortest way, using map to iterate through an array:
var geuploadeAfbeeldingen = $('.afbeeldingen').map(function(k, v) { return v.files[0]; }).get();

Changing a class with z-index

I'm still in the process of learning JavaScript. and I would like to complete the task using only JavaScript and no Jquery.
I have multiple div/images that I’m trying to manipulate using the z-index, and a button that randomize the images to come to the front.
I got the random image array to work but as you could see in image[1]…setting each changeZ index will be laborious. So I’m embarking on changing the class’s (as seen in image[0] so I could add current to the new image and send current to the background on the next go around and then removing the class attribute. I have got the element to work separate but having trouble putting it together in a array.
function changeZIndex(i,id) {
document.getElementById(id).style.zIndex=i;};
function changeClassZIndex(i,tagName){
document.getElementsByTagName("*").style.zIndex=i;};
function getImage(){
var whichImage=Math.floor(Math.random()*3);
var image=new Array()
var currentPhoto = div.current
image[0]=function() {
changeZIndex(5,"scene1");
changeClassZIndex(-5,"current");
currentPhoto.removeClass('current')
document.getElementById("scene1").className += "current"; };
image[1]=function() {
changeZIndex(5,"scene2");
changeZIndex(-5,"scene1");
changeZIndex(-5,"scene3");
changeZIndex(-5,"scene");
};
image[2]=function() {
changeZIndex(5,"scene3");
changeZIndex(-5,"scene");
changeZIndex(-5,"scene2");
changeZIndex(-5,"scene1");
};
image[whichImage].apply(undefined);};
It's because document.getElementsByTagName() returns an array of elements, which you can't do operations like that on. Instead, you need to enumerate through them and do the operations individually.
Here's a working jsfiddle which shows exactly how to do it: jsfiddle
As a side note: if there's one thing a lot of web programming will teach you, its this:
Dont ever, ever, rule out jQuery as an option.
JQuery is your best friend, and the use of it in this situation would cut down your lines of code by well over half.
Firstly, I believe your problem is probably in changeClassZIndex(i,tagName)
which should probably look something like this:
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
function changeClassZIndex(z,className) {
var e = document.getElementsByClassName(className);
for(var i = 0; i < e.length; i++) {
e[i].style.zIndex = z;
}
};
I am defining the getElementsByClassName function if it does not exist because some browsers may not support it.
I may suggest taking a different approach to your problem however:
var images = new Array("scene1", "scene2", "scene3");
var currentPhoto = div.current
var whichImage = Math.floor(Math.random()*images.length);
// change all images to the background
for(var i = 0; i < images.length; i++)
{
changeZIndex(-5, images[i]);
}
// change the one you want to the top
changeZIndex(5, images[whichImage]);
That way you do not have to write functions for each image, and adding images is as easy as adding to the array.

Categories

Resources