Home > database >  Getting CSS values from an element inside an array loop causes an error in jQuery
Getting CSS values from an element inside an array loop causes an error in jQuery

Time:12-01

I'm trying to get the CSS values from each children, do some calculations and then apply it back to each child.

When trying to assign the left CSS value into a variable called X using jQuery i get this error:

Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

Code on how I do it

const wayps = document.querySelector('#waypoints');
const children = wayps.childNodes;
var x,y,canvas_x,canvas_y,px_x,px_y;
children.forEach(function(wayps) {
   
    x = $(wayps).css("left");

});

But applying CSS to each element within the array works with no errors.

   children.forEach(function(wayps) {
        console.log(wayps.innerText); 
// or
       $(wayps).css("left" , 0 "px");
});

Complete code

const wayps = document.querySelector('#waypoints');
const children = wayps.childNodes;
var x,y,canvas_x,canvas_y,px_x,px_y;
children.forEach(function(wayps) {
   
    x = $(wayps).css("left");
    x = x/2;
    $(wayps).css("left" , x "px");

});

HTML as requested

<div id="main">
        <div id="map">
  
        <div id="map_">
        <div id="waypoints">
                <div id="waypoint" class="waypoint_17" style="left: 0px; top: 0px;"></div>   
                <div id="waypoint" class="waypoint_18" style="left: 0px; top: 0px;"></div>
                </div>
            </div>
        </div>
        <div id="frm">
    </div>
    </div>

How do you solve this problem?

CodePudding user response:

I solved my issue. First, I replaced the id with a class like so:

 <div id="waypoint" class="waypoint_17" style="left: 0px; top: 0px;"></div> 

with

  <div class="waypoint" id="waypoint_17" style="left: 0px; top: 0px;"></div> 

Then i used querySelectorAll instead querySelector

document.querySelectorAll('.waypoint');

And finally, to do the calculation, the right way to get the left value is to convert it to an integer by doing so

 x = parseInt($(wayps).css('left'));

And finally the working code

  var  waypsList = document.querySelectorAll('.waypoint'); 
    [].forEach.call(waypsList, function(wayps) {
       
        x = parseInt($(wayps).css('left'));
        x = x/2;
        $(wayps).css("left" , x "px");

});

CodePudding user response:

Node.childNodes return all child nodes including text nodes and comment nodes. The error is most likely caused when jQuery try to get the computed style of the text node before the .waypoint_17 (the text is actually just white space).

You can use document.querySelectorAll("#waypoints > div") to find the exact nodes.

PS: it is incorrect to have duplicate IDs in one document.

  • Related