0

Recently fiddled over this question on stackoverflow:

Dynamically arrange elements around circle

But this solutions includes jquery, and $(this) keywords. I want to convert this code:

function distributeFields(deg) {
    deg = deg || 0;
    var radius = 200;
    var fields = $('.field'), container = $('#container'),
        width = container.width(), height = container.height(),
        angle = deg || Math.PI*3.5, step = (2*Math.PI) / fields.length;
    fields.each(function() {
        var x = Math.round(width/2 + radius * Math.cos(angle) - $(this).width()/2);
        var y = Math.round(height/2 + radius * Math.sin(angle) - $(this).height()/2);
        if(window.console) {
            console.log($(this).text(), x, y);
        }
        $(this).css({
            left: x + 'px',
            top: y + 'px'
        });
        angle += step;
    });
}

this is what i tried to do before getting stuck at ($this) keyword:

function distributeFieldsJS(deg){
  deg = deg || 0;
  let radius = 200;
  let fields = document.querySelectorAll('.field'), 
  container = document.querySelector('#container'),
  width = container.width(), height = container.height(),
  angle = deg || Math.PI * 3.5, 
  step = (2*Math.PI) / fields.length;
  })
k1st
  • 81
  • 7
  • 1
    NodeList now has a forEach function. So you can use it. First arg should be the element so you do not need `$(this)` – Rajesh Jan 18 '21 at 04:37

1 Answers1

1

It's inside a jQuery each callback, so it refers to the element currently being iterated over, so you just need to do

for (const field of fields) {
  // refer to `field` here
}

and the field will be the native DOM element. (just like how $(this) referred to the same element wrapped in jQuery).

getBoundingClientRect will give you its dimensions. field.textContent will retrieve its text. field.style will give you the CSSStyleDeclaration of the element.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320