0

Lets say I have an array of variables, I want to iterate through the array and change only a specific variable. Here's an example at the top of my head to illustrate what I mean.

function click() {
    var p1 = document.getElementById("p1");   //a paragraph
    var p2 = document.getElementById("p2");   //a paragraph
    var img = document.getElementById("img"); //an image
    var arr = [p1, p2, img];
    for(i = 0; i < arr.length; i++) {
        //Herein lies the problem
        if (arr[0] == img) {   ---Or---  if (i == newarr.indexOf(img)) {

            arr[0].style.display = "none";
        }
    }
}

In the snippet above, both if conditions do not work. How do I check if an element is a specific variable?

2 Answers 2

2

Use like this:

for(var i = 0; i < arr.length; i++) {
    if (arr[i] === img) { 
        arr[i].style.display = "none";
    }
}

You can do it also like:

arr.forEach(function(v){
  if(v===img) v.style.display = "none";
});
Sign up to request clarification or add additional context in comments.

Comments

2

Use this case

var arr = [p1, p2, img];
if (arr.indexOf(img) != -1) {
   var pos = arr.indexOf(img);
   arr[pos].style.display = "none";
}

Hope this Works.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.