Getting through all entries in JS by queryselector - javascript

I'm trying to get some informations from the page.
If there is one entry I can do that by
var z = document.querySelector('div.class').innerText;
and then get it by +z somewhere where I need the value.
But if there are more entries it will get only first.
I'm trying to do sth like that to get them all:
var x = document.querySelectorAll('div.class');
var i;
for (i = 0; i < x.length; i++) {
x[i].innerText;
}
But definitely something's wrong with this code. I'm not really familiar with JS, could you help me how to get all entries?

You can achieve that by using getElementsByClassName('class').
The script would be sort of:
let list = document.getElementsByClassName('class');
for (let i = 0; i < list.length; i++) {
console.log(list[i].innerText);
}
https://jsfiddle.net/esjcaqwb/

Your code looks ok, heres a working example that might be useful.
var x = document.querySelectorAll('.example');
var r = document.querySelectorAll('.result')
var i;
for (i = 0; i < x.length; i++) {
r.innerText += x[i].innerText;
}
What was going wrong with your code? In the example you provided, you're getting the value but not doing anything with it.

With your actual code you are not doing anything in the loop, the statement x[i].innerText; does nothing.
If you want to get these elements contents in an array you can use:
var results = Array.from(x).forEach(function(el){
return el.innerText;
});

Related

JS JSON process

I'm new in JSON handling, so I would like to get some help :)
I have this data in the data variable:
{"json":null,"id":"1111","prime1":"26","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"2111","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"3111","prime1":"11","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"4111","prime1":"4","prime2":"0","ass1":"17","ass2":"13","time1":"07:00:00","time2":"17:30:00"}*{"json":null,"id":"5111","prime1":"6","prime2":"0","ass1":"23","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"6111","prime1":"1","prime2":"0","ass1":"15","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"1112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"2112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"3112","prime1":"22","prime2":"0","ass1":"18","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"4112","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"5112","prime1":"3","prime2":"0","ass1":"19","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"6112","prime1":"9","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"1121","prime1":"3","prime2":"0","ass1":"15","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"2121","prime1":"6","prime2":"0","ass1":"23","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"3121","prime1":"11","prime2":"0","ass1":"0","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"4121","prime1":"8","prime2":"0","ass1":"17","ass2":"13","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"5121","prime1":"22","prime2":"0","ass1":"19","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"6121","prime1":"1","prime2":"0","ass1":"12","ass2":"0","time1":"07:00:00","time2":"14:30:00"}*{"json":null,"id":"1122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"2122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"3122","prime1":"0","prime2":"0","ass1":"0","ass2":"0","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"4122","prime1":"8","prime2":"0","ass1":"13","ass2":"18","time1":"14:00:00","time2":"21:30:00"}*{"json":null,"id":"5122","prime1":"22","prime2":"0","ass1":"19","ass2":"0","time1":"14:00:00","time2":"21:30:00"}
I can't create objects from them.
This is my code:
var dataSplit = data.split("*");
for (var i = 0; i < dataSplit.length; i++) {
objects[i] = dataSplit[i];
document.getElementById("proba").innerHTML += objects[i].time2;
}
Thanks for all of you!
It's working now, it was 2 hours for me. The problem was I didn't initialize the object array and didn't use JSON.parse() (tried the JSON.parse() before, without success). So the solution is:
var objects = [];
var dataSplit = data.split("*");
for (var i = 0; i < dataSplit.length; i++) {
objects[i] = JSON.parse(dataSplit[i]);
document.getElementById("proba").innerHTML += objects[i].time2;
}

JavaScript - What is wrong with my Hash Table?

I am doing the first problem on LeetCode, Two Sum. I am trying to do the problem using a hash table. This is what I came up with:
var twoSum = function(nums, target) {
var hash = [];
for(var i = 0; i < nums.length; i++) {
var need = target - nums[i];
if (!hash[need]) {
hash[need] = i;
} else {
return [hash[nums[i]], i];
}
}
};
When I run my code, I am getting undefined as an answer. Let's say I have an array [2,3,1,6,4] and my target is 8. When I iterated through the array, I will get 8-2=6, 8-3=5, 8-1=7, 8-6=2, and 8-4=4. So, my hash table should look like this according to my code:
6:0
5:1
7:2
2:3
4:4
If something is not in the hash table, I want to throw it into the hash. When I run into the number in the hash, then I return hash[nums[i]] and i since I am ready at the index and hash[nums[i]] has the value of the index that I need. I am unsure why I am getting an undefined. Any advice to make this better?
Please see the code. I have removed the else part and returned the hash at end. Please let me know if this is what you were looking.
var twoSum = function(nums, target) {
var hash = [];
for(var i = 0; i < nums.length; i++) {
var need = target - nums[i];
if (!hash[need]) {
hash[need] = i;
}
}
return hash;
};
console.log(twoSum([2,3,1,6,4],8))

which is faster in a for loop, accessing values using temp variable or the index?

I am trying to optimize some knockout js code and I was wondering which would be faster, ie accessing the variable using the indexer as so:
for (var i = 0; i < data.length; i++) {
data[i].MediaID = ko.observable(data[i].MediaID);
data[i].MediaName= ko.observable(data[i].MediaName);
data[i].MediaTypeID= ko.observable(data[i].MediaTypeID);
}
or declaring a temp variable.
for (var i = 0; i < data.length; i++) {
var temp = data[i];
temp.MediaID = ko.observable(temp.MediaID);
temp.MediaName= ko.observable(temp.MediaName);
temp.MediaTypeID= ko.observable(temp.MediaTypeID);
}
Accesing with the temp-variable should be slightly faster because you don't need to look up the element in the array.
However, the gain will be minimal
compare
data.a.b.c.d.e.f.g.MediaID = ko.observable(data.a.b.c.d.e.f.g.MediaID);
data.a.b.c.d.e.f.g.MediaName= ko.observable(data.a.b.c.d.e.f.g.MediaName);
data.a.b.c.d.e.f.g.MediaTypeID= ko.observable(data.a.b.c.d.e.f.g.MediaTypeID);
and
var temp =data.a.b.c.d.e.f.g;
temp.MediaID = ko.observable(temp.MediaID);
temp.MediaName= ko.observable(temp.MediaName);
temp.MediaTypeID= ko.observable(temp.MediaTypeID);
you don't need to look up the same thing so many times
if you want it faster you should also cache data.length
for(var i = 0, len = data.length; i < len; i++)...
If you are concerned about performance don't use array.length in the loop. That is not a value, is a internal function that everytime that is accessed recount the total items of the array, the better is:
var total = items.length;
for(i=0; i < total; i++){
//stuff
}
Now for your specific use case, I do not know the framweworks that you are using on, but if you are using jQuery and / or underscore, instead of a loop, you could use one of the map functions:
http://api.jquery.com/jQuery.map/
http://underscorejs.org/#map

give random number on last created class JavaScript

Im trying to give the last created class a number, I know that in Jquery i could use :last but how is it in JavaScript ?
I have tried a loop but it does not really do it ? Any suggestions ?
This is what i have for now.
var x=document.getElementsByClassName("sticker");
for (var i = 0; i<x.length; i++){
x.innerHTML=Math.floor((Math.random()*1000000)+1);
<div class="sticker"></div>
<div class="sticker"></div>
<div class="sticker">155477</div>
I'm not sure that i fully understood what you mean but i think that you want the following:
var x=document.getElementsByClassName("sticker");
x[x.length-1].innerHTML=Math.floor((Math.random()*1000000)+1);
Try
var x=document.getElementsByClassName("sticker");
x[x.length - 1].innerHTML=Math.floor((Math.random()*1000000)+1);
You can just get the last element in the collection by using the length for index computation:
var x = document.getElementsByClassName("sticker");
if (x.length)
x[x.length-1].innerHTML = Math.floor((Math.random()*1000000)+1);
Simply check for the last iteration of your loop:
for (var i = 0; i < x.length; i++){
if (i == x.length - 1) {
x[i].className = x[i].className + " newclass";
}
}

Finding an object and returning it based on search criteria

I have been searching online all day and I cant seem to find my answer. (and I know that there must be a way to do this in javascript).
Basically, I want to be able to search through an array of objects and return the object that has the information I need.
Example:
Each time someone connects to a server:
var new_client = new client_connection_info(client_connect.id, client_connect.remoteAddress, 1);
function client_connection_info ( socket_id, ip_address, client_status) {
this.socket_id=socket_id;
this.ip_address=ip_address;
this.client_status=client_status; // 0 = offline 1 = online
};
Now, I want to be able to search for "client_connection.id" or "ip_address", and bring up that object and be able to use it. Example:
var results = SomeFunction(ip_address, object_to_search);
print_to_screen(results.socket_id);
I am new to javascript, and this would help me dearly!
Sounds like you simply want a selector method, assuming I understood your problem correctly:
function where(array, predicate)
{
var matches = [];
for(var j = 0; j < array.length; j++)
if(predicate(j))
matches.push(j);
return matches;
}
Then you could simply call it like so:
var sample = [];
for(var j = 0; j < 10; j++)
sample.push(j);
var evenNumbers = where(sample, function(elem)
{
return elem % 2 == 0;
});
If you wanted to find a specific item:
var specificguy = 6;
var sixNumber = where(sample, function(elem)
{
return elem == specificguy;
});
What have you tried? Have you looked into converting the data from JSON and looking it up as you would in a dictionary? (in case you don't know, that would look like object['ip_address'])
jQuery has a function for this jQuery.parseJSON(object).
You're going to need to loop through your array, and stop when you find the object you want.
var arr = [new_client, new_client2, new_client3]; // array of objects
var found; // variable to store the found object
var search = '127.0.0.1'; // what we are looking for
for(var i = 0, len = arr.length; i < len; i++){ // loop through array
var x = arr[i]; // get current object
if(x.ip_address === search){ // does this object contain what we want?
found = x; // store the object
break; // stop looping, we've found it
}
}

Categories