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.
Related
I am building a plugin for a CMS that has lots of different templates. As part of the plugin I am pulling text from a specific description box on the page. The problem is that every template has a different class name for the description box. I have gotten the plugin to work on a specific template that uses ".class1" but I would like to make it work no matter what template its installed on.
I basically want to put the class names from each template in an array and then check and see which one is on the page. I then want to store the matched class name in a variable that I can use.
This will loop through an array of classes and check to see if there are any elements matching each class on the page. The matched class names get pushed into a new array.
var classes = [".abc", ".def", ".ghi"];
var found = [];
for(var i = 0; i < classes.length; i++) {
if($(classes[i]).length > 0) {
found.push(classes[i]);
}
}
If you're certain that only one class in the initial list will be found, you can stop after your first hit:
var classes = [".abc", ".def", ".ghi"];
var found;
for(var i = 0; i < classes.length; i++) {
if($(classes[i]).length > 0) {
found = classes[i];
break;
}
}
You can use document.querySelector() to find the element with one of the classes.
Note that if you want to find more than one instance - document.querySelectorAll() will create a node list.As #Hydrothermal says - if there are multiple elements with that class - you will need to push them into an array and using an index [0] to identify them.
var templates = ["first-template", "second-template", "third-template"];
var currentTemplate;
templates.forEach(function(template){
let test = document.querySelector("." + template);
if(test !== null) {currentTemplate = template};
})
console.log(currentTemplate); // gives secondTemplate
<div class="second-template">I am a template</div>
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
So I save my array as a variable: var arrayContents = contentData;
and my array: ['content_1', 'content_2', 'content_3', 'content_4']
So i've got my array, I then want to place it into my HTML which i've done via using text like such: $('.container').text(arrayContents);
I need to break my text up so it currently looks like:
And i'm trying to get it to look like :
How can I break my array up so each item drops onto a new line? As when I use .text I print the whole array as one not each separate item.
Use a foreach loop and add a <br> tag to go to next line:
var contentToInsert;
$.each(arrayContents,function(value){
contentToInsert += value + "<br>";
});
$('.container').html(arrayContents);
You need to use html() instead of text(), check this
var htm = '';
var arrayContents = ['content_1','content_2','content_3'];
arrayContents.forEach(function(item){
htm += item + '<br />'; // break after each item
});
$('.container').html(htm);
Actually .text() works with a string value. You passed an array, which leads the "engine" to call arrayContents.toString() to get a string from the array. As you can see there, this function separates each entry by a comma.
If you want to produce an output on one column, you have to generate HTML (as shown in this answer), or editing the div object through javascript DOM functions (fiddle) :
for (var i = 0; i < arrayContents.length; i++) {
var currentElement = document.createElement("DIV"); // "DIV" or block-type element
var currentText = document.createTextNode(arrayContents[i]);
currentElement.appendChild(currentText);
document.getElementById("container").appendChild(currentElement);
}
Be sure of what kind of HTML you want to produce.
Here is my javascript array:
var quizArray = [
'When the weather is agreeable what do you prefer to do the most?~Something outside...Obviously!~I tend to enjoy things that aren\'t dependent on weather.~Read, possibly outside if I can find my sunscreen.~Do what I always do, which is whatever I want.~Try something new, like Planking.~~~','It\'s a weeknight and friend invites you to an orchestra. You would?~Kindly refuse. It\'s just not my thing.~Go, unquestionably. I love all art forms.~Ask who the composer is, then read all about them before going.~Confuse Orchestra with Opera and begin singing in Latin.~Go if the tickets are free, otherwise no.~~~',]
When I load my html it won't display line breaks after each answer. I've tried adding a .join(<\br>) after split, but that breaks up every single word, here is the code I have:
function displayQuiz(ent, qnum) {
perPage++;
var qna = quizArray[qnum].split('~');
var od = []; for (var i = 1; qna[i] != null && qna[i] != ''; i++) od.push(i); od.sort( randOrd ); od.sort( randOrd );
var newF = document.createElement("form");
var newDq = document.createElement("div");
newDq.className = 'question';
newDq.appendChild(document.createTextNode(Number(qnum+1)+ ': ' +qna[0]));
newF.appendChild(newDq);
newDq = document.createElement("div");
newDq.className = 'answers';
for (var i = 1; qna[i] != null && qna[i] != ''; i++) {var newDa = document.createElement("label"); newDa.htmlFor = 'a'+qnum+i; /*#cc_on #if (#_jscript) var newR = document.createElement("<input name='a"+qnum+"'>"); #else */
var newR = document.createElement("input");
newR.name = 'a'+qnum; /* #end #*/
newR.type = 'radio';
newR.id = 'a'+qnum+i;
newR.value = od[i-1];
newDa.appendChild(newR);
newDa.appendChild(document.createTextNode(' '+qna[od[i-1]]+' '));
newDq.appendChild(newDa);}
newF.appendChild(newDq);
document.getElementById('quiz'+perPage).appendChild(newF);
}
I'll try my best to post additional info if needed. I did use this as a snippet and am very novice on Javascript. Not opposed to learning on my own but I've poured over the interwebs and cannot find my answer.
to make an array of Strings its better if you put your complete string in a var and after make a split(), and for add you can use a join() or a for()
It's better put this way the code
var quizArray = 'When the weather is agreeable what do you prefer to do the most?~Something outside...Obviously!~I tend to enjoy things that aren\'t dependent on weather.~Read, possibly outside if I can find my sunscreen.~Do what I always do, which is whatever I want.~Try something new, like Planking.~~~';
function displayQuiz(ent, qnum) {
perPage++;
var qna = quizArray.split('~');
var res = qna.join(" <br> ");
return res;
}
Here is the approach that I took, using .join to add the br element. I think you weren't specifying what to split on originally, if it added br after every word.
var string = 'When the weather is agreeable what do you prefer to do the most?~Something
outside...Obviously!~I tend to enjoy things that aren\'t dependent on weather.~Read, possibly outside if I can find my sunscreen.~Do what I always do, which is whatever I want.~Try something new, like Planking.~~~';
var quizArray = string.split('~');
var finalString = quizArray.join('<br/>');
document.getElementById('yourIdHere').innerHTML = finalString;
Here's a fiddle: http://jsfiddle.net/brettwlutz/Q35J2/1/
i thought arrays were made as so:
var arr = [val1, val2, val3];
you can use arr.push to append more values or arr.unshift to add values to the beginning of the array
http://jsfiddle.net/h_awk/K3kEv/
<script>
var arr = [1, 2, 3, 4], i;
for( i=0; i<arr.length; i++ )
{
document.write(arr[i] + '<br />');
}
</script>
First, to answer your question. The above code should work and make the variable qna contain the new, split array. Your solution of adding .join("") should then turn that new array into a single string with html newlines. That is, unless you want t JS newline, in which case you should instead use .join("\n").
My question for you is, why are you starting with an array with only one element? A string can be split into an array and joined back into a string the same way. Also, it may be easier to, instead of using the tilde ~ to seperate the statements you want to split, just use a form of proper array syntax, then get rid of the "split" and just use the joining:
var quizArray = ["When the weather is agreeable what do you prefer to do the most?", "Something outside...Obviously!, I tend to enjoy things that aren\'t dependent on weather.", "Read, possibly outside if I can find my sunscreen.", "Do what I always do, which is whatever I want.", "Try something new, like Planking."];
My only possible understanding is that you are still learning JS and this is just an example for learning how to split arrays, but this is not really a real-life application, which is why this post seems questionable to Stack Overflow users.
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!