简体   繁体   中英

How to select elements to apply a transformation(rotation, etc) to?

I am trying to rotate or transform all elements inside a div but I currently have this function. It rotates all elements on the page. How can I select a div or a class to rotate instead? Array.from(document.all).forEach(o => o.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)")

You need to use document.getElementsByClassName() or document.getElementsByTagName() :

var selected = document.getElementsByClassName('myClass');
Array.from(selected).forEach(o => o.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)")
function randomRotate(selector) {
  var elem = document.querySelector(selector);
  if (!elem) return;
  elem.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)"
}

randomRotate('.someClass');

Basically it doest the same as your code, but instead of taking all elements it looks for particular via selector. If there are multiple elements with such class it will apply rotation only for first of them.

So if you want to apply rotation to all objects with that class, you should use a bit another function:

function randomRotate(selector) {
  var elems = document.querySelectorAll(selector);
  if (elems.length === 0) return;
  elems.forEach(function(el){
    el.style.transform = "rotate(" + Math.floor(Math.random() * 27 - 12) + "deg)"
  })
}

randomRotate('.someClass')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM