Select ALL getElementsByClassName on a page without specifying [0] etc

旧城冷巷雨未停 提交于 2020-01-06 15:18:12

问题


I am trying to create a function as part of a WordPress site, to show/hide page elements with a certain class. E.g. any page elements (rows, containers, text-blocks etc.) that use the class 'show-hide', should be hidden/shown with the click of a button.

I have got it working, but I'm sure there must be a better method to achieve a similar result. I'd like to be able to select ALL the show-hide classes on the page without specifying a number ( [1], [2], [3], [3], [6]... ) for each time it's used.

I'm really new to javascript, so any help or advice, on generating a range of values or using wildcard * symbols to achieve this would be appreciated.

function myFunction() {
  var x = document.getElementsByClassName("show-hide");

  if (x[0].style.display === "none") {
    x[0].style.display = "block";
  } else {
    x[0].style.display = "none";
  }
  if (x[1].style.display === "none") {
    x[1].style.display = "block";
  } else {
    x[1].style.display = "none";
  }
  if (x[2].style.display === "none") {
    x[2].style.display = "block";
  } else {
    x[2].style.display = "none";
  }
  if (x[3].style.display === "none") {
    x[3].style.display = "block";
  } else {
    x[3].style.display = "none";
  }
}

回答1:


As answered above you can use a loop. Here's a shorthand:

for(let elem of Array.from(document.getElementsByClassName("show-hide"))) {
   elem.style.display = (elem.style.display === 'block') ? 'none' : 'block';
}



回答2:


You can make an array from your HTML Collection and simply use map :

function myFunction() {

  Array.from(document.getElementsByClassName("show-hide")).map(function(elem){
    if (elem.style.display === "none") { 
      elem.style.display = "block" 
    } else {
      elem.style.display = "none";
    }
  })

};



回答3:


As noted int the comments, you're looking for looping:

function myFunction() {
  var x = document.getElementsByClassName("show-hide");

  [...x].forEach(xx => {
    if (xx.style.display === "none") {
      xx.style.display = "block";
    } else {
      xx.style.display = "none";
    }
  });
}

Note the [...x] spread operator which will convert an itterable (HTMLCollection in this case) to an array.



来源:https://stackoverflow.com/questions/55815521/select-all-getelementsbyclassname-on-a-page-without-specifying-0-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!