Search code examples
javascriptcometd

showing selected names in a <div> by using a javascript array


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.


Solution

  • 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.