Questions about the Code examples of Chapter 10 of the Art of Javascript DOM programming, 2nd Edition

the code is as follows

function moveElement(element,final_x,final_y,interval) {
  if (!document.getElementById) return false;
  if (!document.getElementById(element)) return false;
  var elem = document.getElementById(element);
  if (elem.movement) {
    clearTimeout(elem.movement);
  }
  if (!elem.style.left) {
    elem.style.left = "0px";
  }
  if (!elem.style.top) {
    elem.style.top = "0px";
  }
  var xpos = parseInt(elem.style.left);
  var ypos = parseInt(elem.style.top);
  if (xpos == final_x && ypos == final_y) {
    return true;
  }
  if (xpos < final_x) {
    var dist = Math.ceil((final_x - xpos)/10);
    xpos = xpos + dist;
  }
  if (xpos > final_x) {
    var dist = Math.ceil((xpos - final_x)/10);
    xpos = xpos - dist;
  }
  if (ypos < final_y) {
    var dist = Math.ceil((final_y - ypos)/10);
    ypos = ypos + dist;
  }
  if (ypos > final_y) {
    var dist = Math.ceil((ypos - final_y)/10);
    ypos = ypos - dist;
  }
  elem.style.left = xpos + "px";
  elem.style.top = ypos + "px";
  var repeat = "moveElement(""+element+"","+final_x+","+final_y+","+interval+")";
  elem.movement = setTimeout(repeat,interval);
}

this code is extracted from a variable elem, in Chapter 10
of the Art of Javascript DOM programming Edition 2. If I change it to get the node through the class name or item 0 in the tag signature,
for example

var elem = document.getElementsByTagName(element)[0];

var elem = document.getElementsByClassName(element)[0];

in this way, the running function will report an error, and only by getting the node through id can it work normally. I really don"t understand

.

what is the principle of this, dear gods? Thank you

Jul.23,2021

so what is the element value you pass in.


the parameters obtained by these methods end up as strings. As long as you make sure that what you pass in is the correct existing id name, type, and tag signature, the method itself should be fine.
look at your error report, it should be that the getElementsByTagName method of the object is not found, and whether document is misspelled.

also if (! document.getElementById (element)) return false; Don't forget to modify this judgment.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1eb0609-48092.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1eb0609-48092.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?