I've tried to look around for the past half hour but I don't believe anyone has asked this before, as I cannot find an answer. How do I specify different CSS for each element within an array. Preferably appending a class to the array element to limit redundancy.
var Stat = new Array();
Stat[0] = "<span class='good'>Alive</span>";
In other words I want to accomplish the above.
I hope that I'm understanding your question properly. You could just iterate through the array and append a class with a prefix followed by the index. Please let me know if I'm not following your question correctly.
var Stat = new Array();
for (var i = 0; i < 6; i++) {
Stat.push('<span class="good' + i + '">Alive</span>');
}
// Produces an array with the following:
<span class="good0">Alive</span>
<span class="good1">Alive</span>
<span class="good2">Alive</span>
<span class="good3">Alive</span>
<span class="good4">Alive</span>
<span class="good5">Alive</span>
To populate the array with your HTML/CSS code you can do the following:
var Stat = new Array();
Stat.push("<span class='good'>Alive</span>");
Stat.push("<span class='bad'>Dead</span>");
Stat.push("<span class='evil'>Hell</span>");
After the code above your array Stat will have the following content:
Stat[0] == "<span class='good'>Alive</span>";
Stat[1] == "<span class='bad'>Dead</span>";
Stat[2] == "<span class='evil'>Hell</span>";
Each push create a new array position with a incremental index.
Hope it can help you!
Related
Im currently quite new to javascript and im just trying to learn some basic things. Im not so bad in other languages so i do understand concepts etc.
I have a table with 10 rows for example, One of the cells is a "CaseID" and it exists for every row. Im trying to use the Math.Random property to generate random numbers.
My problem i hit first was i was using the ID property in my HTML and obviously this is unique, next i used class. I tried to append the output with an index but this again only worked for the first cell and nothing for the rest.
HTML:
<td class="caseID"></td>
JS:
var caseID = Math.floor((Math.random() * 10000));
document.getElementsByClassName("caseID")[0].innerHTML = caseID;
This all works great for the first cell/row but every other row returns blank. Im assuming because i need to perhaps create an array/indexing but im unsure on how to do this.
Could i create a variable:
var tds = document.getelementsbyclassname("caseID");
And maybe write a foreach etc? again not sure on how to do this.
Thanks in advance!
You can try a foreach like this, which would be a lighter syntax
document.getElementsByClassName("caseID").forEach(function(element) {
var caseID = Math.floor((Math.random() * 10000));
element.innerHTML = caseID;
})
You can use a good old for loop, use a more "separate the steps" way which could help you understand more how javascript works. I will use querySelectorAll but you can do it with getElementsByClassName
var myTds = document.querySelectorAll('caseID');
// You don't want to calculate the length at each loop
for (var i = 0, length = myTds.length; i < length; i++) {
var caseID = Math.floor((Math.random() * 10000));
var element = myTds[i];
element.innerHTML = caseID;
}
Hope it helps
How about this:
var tds = document.getElementsByClassName("caseID");
if ( tds.length ) { // just a check to make sure you've found somethiung
var caseID = Math.floor((Math.random() * 10000));
for(i = 0; i < tds.length; i++) {
tds[i].innerHTML = caseID;
caseID = Math.floor((Math.random() * 10000));
}
}
You can do this by write a foreach for class element in javascript.
var cases_list = document.querySelectorAll('.caseID');
Array.prototype.forEach.call(cases_list, function(elements, index) {
// conditional here.. access elements
});
OR if you use jquery than you can do this by
$('.caseID').each(function(index, obj){
//you can use this to access the current item
});
I am new to js and I don't understand much of codes and conditions in js.
My question is simple but I need someone to give me a good example if possible as I know what I need but it is getting hard to implement that in code.
This is my code with 2 arrays where the data is coming from.
blind_tmp = '';
for (i=0; i<#All of Blind Relationship Link.length; i++){
blind_tmp = blind_tmp + '<p>[**' + #All of Element Title[i] + '**](' + #All of Blind Relationship Link[i] + ')'
};
What simple needed is that. I want merge records that are duplicates printed.
for example: if Blind Relationship link is AF44 and after 6 elements this AF44 comes again so I want both to be written like 1.AF44,2.AF44
while now it is writing the elements how they come along
example:
AF11,AF22,AF33,AF44,AF55,AF66,AF77,AF44
so in this example you see two AF44
I want them to be written like this
AF11,AF22,AF33,AF44AF44,AF55,AF66,AF77
any help with a code example is appreciated.
The idea is to iterate through each element in the blindRelationshipLink and store those elements in a temporary array which will be used to check the number of occurrence of an array element.
var blindRelationshipLink = ['AF11','AF22','AF33','AF11','AF44','AF44','AF55','AF66','AF77','AF11','AF22','AF11'];
var arrTemp = [];
var p = '';
blindRelationshipLink.forEach(function(arr){
var count = 0;
arrTemp.forEach(function(a){
if(arr === a)
count++;
});
arrTemp.push(arr);
if(count){
count++;
arr= arr + '.' + count;
}
p = p + arr + ',';
});
alert(p);
You test by running the code snippet.
This approach is not best but it may serve your purpose.
Here is a snippet
var elemArray = ['AF11', 'AF22', 'AF33', 'AF44', 'AF55', 'AF66', 'AF77', 'AF44']; // Array of elements
//A new array which which will contain elements which pass our case
var finalArray = [];
elemArray.forEach(function(item) { // loop through main array
// Check if element is present or else push the element
if (finalArray.indexOf(item) == -1) {
finalArray.push(item);
} else {
// if element is there find the index
var getIndex = finalArray.indexOf(item);
// remove the element, else there will be duplicate
finalArray.splice(getIndex, 1);
//concate the matched element
var newElem = item + item;
// push the element in specfic index
finalArray[getIndex] = newElem;
}
})
console.log(finalArray)
Current drawback with this code is what will happen if there are multiple repeated item in the main array. For example presence of AF33 more than twice.
DEMO
I have to save temporary data for my webpage using java script.This is the way that i save i one by one since the data is an array.
var product= new Array();
product[1] = document.getElementById("product[1]").value;
product[2] = document.getElementById("product[2]").value;
This method is working. but when i run it by looping, it doesnt work.
for(var i=1; i < no_item; i++){
product[i] = document.getElementById("product[i]").value;
}
*product[] is a varibale that I take from a html dropdown menu
Can anyone please tell me the problem ? thanks ~ =)
Should be written as, as you are going to be getting the id "product[i]" every time with your original code. This will get "product[1]" then "product[2]" and so on:
for(var i=1; i < no_item; i++){
product.push(document.getElementById("product[" + i + "]").value);
}
Also, as a comment, we tend to prefer var product = []; over var product = new Array(); in javascript but both will work.
I have a div which displays name of the people who are online, I have the following members in
the div
<div id="members">
<span>Amlan Karmakar</span>
<span>Atin Roy</span>
<span>Arpan Burman</span>
<span>Ramanuj Mukherjee</span>
</div>
I have another javascript array friends[], which has 'Amlan Karmakar' and 'Ramanuj Mukherjee' has friends, I want to display those members who are in the friends[] array, I am inserting the name of the friends by friends.push("Amlan Karmakar"). The names in div are auto generated by cometd chat, I have written the names in the div for simplicity. I hope there is a solution to this problem. My previous question didn't solve my problem.
You could try something like the below, i.e. split the HTML of the div containing the members, loop through them and check if they are in the friendsArray. Note that this is a rough implementation, and that it assumes a reasonably new browser as it uses Ecmascript 5 features. The concept can applied using old-fashioned for loops too.
var all = document.getElementById('members').getElementsByTagName('span');
var friendsOnly = '';
for(var i=0; i<all.length; i++){
if(friendsArray.some(function(friend){
return friend == all[i].innerHTML;
})){
friendsOnly += '<span>' + all[i].innerHTML + '</span>';
}
});
all.innerHTML(friendsOnly);
By the way, I'm assuming the friendsArray may contain people who are not already in the div. If that is not the case, then I'm not sure what the question is about.
So you want to put the data from the friends[] array into the <div id="members">
I want only those names to show in the which are there in the friends[] array
If you only want to display the names which are in the friends array, as you suggested in your comment, I suppose this will do the trick:
var target = document.getElementById("members");
// Remove this line if you want to keep the current names in the members div.
target.innerHTML = ""; // Clean before inserting friends
for (var i = 0; i <= friends.length; i++) {
target.innerHTML += friends[i] + "<br />"; // Add friend + break
}
Try this to get only the friends out of the list of members:
var friendMembers = document.getElementById('members').split(/<br\s*[\/]?>/gi)
.filter(function(member) { return (friends.indexOf(member) > -1) } );
You should try knockout.js, this framework will help you handle this case.
I need to get the text that is inside a element.
I can only grab the class of this element and NOT the ID.
<span class="fileName">test.png</span>
So I need a way to get test.png, but as you see I have only the class of the element and not the ID.
Just notice also that we may have more <span class="fileName"></span>, so it could look like this
<span class="fileName">test1.png</span>
<span class="fileName">test2.png</span>
<span class="fileName">test3.png</span>
<span class="fileName">test4.png</span>
In the case we have more, like the example above, I need to get ALL the values and not only one, because I need to pass this value to another page with jQuery. So it should be able to get one value or more from that element.
Please help!
And also I am not a javascript expert!
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get();
The array filenames will contain all the names of the images. You can pass on this array to another jQuery function, or anywhere else you like to do so.
You can test it here ยป
Update
Since you request the filenames to be a string separated by a comma, you can do it like this:
var filenames = $('.fileName').map(function(){
return $(this).text();
}).get().join(',');
Now, filenames will contain the string test1.png,test2.png,test3.png,test4.png.
Use document.getElementsByClassName: http://jsfiddle.net/pCswS/.
var elems = document.getElementsByClassName("fileName");
var arr = [];
for(var i = 0; i < elems.length; i++) {
arr.push(elems[i].innerHTML);
}
alert(arr);
(Since you didn't tag the question with jQuery I assume you have to do it with plain JavaScript.)
$('span.fileName').each(function() {
var fileName = $(this).text();
doSomethingWithFileName(fileName);
});
Here the span.fileName selector returns all spans with class fileName then we iterate through, reading the text from each one. You may want to find a container element first and then only iterate inside that, e.g.
var $container = $('#myFileNames');
$container.find('span.fileName').each( ... );
Here's my take:
var spans = document.getElementsByClassName('fileName');
var values = [];
for(var i = 0; i < spans.length; i++) {
values.push(spans[i].innerHTML);
}
// Example of processing: alert the values
alert(values);
Use the following jQuery selector
$("span.fileName").html()