I have a series of divs with class ".newColor". When one of these divs is clicked its contents is converted into a string and added to an array called myArray using the push method only if it is not already listed in the array. Then, myArray is converted back into a series of divs with class ".removeItem" and displayed above a horizontal line.
How can I click on these ".removeItem" divs, and have the divs content (its string) removed from myArray in a similar fashion to how it was added? As in it looks at the divs content, converts it into a string and removes that string from the array if it exists.
var myArray = [];
var myArrayLength;
var newItem = "";
$( ".newColor" ).click(function() {
newItem = $(this).text();
$( '#displayArray' ).html('');
if(myArray.indexOf(newItem) == -1) {
myArray.push(newItem);
myArrayLength = myArray.length;
}
for (var i = 0; i < myArrayLength; i++) {
$( '#displayArray' ).append( '<div class="removeItem">' + myArray[i] + '</div>');
}
});
.newColor, .removeItem {
border: 1px solid black;
cursor: pointer;
margin: 2px;
padding: 2px;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current array:
<span id="displayArray"></span>
<hr>
Add to array:
<div class="newColor">blue</div>
<div class="newColor">red</div>
<div class="newColor">green</div>
<div class="newColor">orange</div>
<div class="newColor">purple</div>
<div class="newColor">yellow</div>
<div class="newColor">brown</div>
<div class="newColor">pink</div>