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?

asked Dec 13, 2014 at 18:26

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";
});
Roko C. Buljan
209k41 gold badges335 silver badges347 bronze badges
answered Dec 13, 2014 at 18:28
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.

answered Dec 13, 2014 at 18:37

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.