admin管理员组

文章数量:1186277

I am getting focused element target with selection API this way below

const target = window.getSelection()?.focusNode;

And when the focusNode is #text HTMLElement, I would want to get the #text Node parent node by doing the following below

console.log((target as HTMLElement));
console.log((target as HTMLElement).parentNode as HTMLElement);
((target as HTMLElement).parentNode as HTMLElement)?.append(
  rows
);
((target as HTMLElement).parentNode as HTMLElement)?.append(
  '<click here to continue new line>'
);
(((target as HTMLElement).parentNode as HTMLElement)?.childNodes[
  ((target as HTMLElement).parentNode as HTMLElement)?.childNodes.length - 1
] as HTMLElement).innerHTML = '<click here to continue new line>';

This works all the time on chrome, but work on mozilla and fails sometimes along the line where I want to get the parent Node.

((target as HTMLElement).parentNode as HTMLElement) returns null 

I have tried to run them in a setInterval function below but it still not working.

let counter = 0;
const tt = setInterval(() => {
  const 
    t1 = (target as HTMLElement),
    t2 = ((target as HTMLElement).parentNode as HTMLElement)
  ;
  if(t1 !== null && t2 !== null) {
    ((target as HTMLElement).parentNode as HTMLElement)?.append(
      rows
    );
    ((target as HTMLElement).parentNode as HTMLElement)?.append(
      '<click here to continue new line>'
    );
    (((target as HTMLElement).parentNode as HTMLElement)?.childNodes[
      ((target as HTMLElement).parentNode as HTMLElement)?.childNodes.length - 1
    ] as HTMLElement).innerHTML = '<click here to continue new line>';
    clearInterval(tt);
  }
  else {
    if(counter > 30) {
      clearInterval(tt);
    }
  }
  counter++;
}, 1);

Please I need help on how to solve this problem in such a way that as long as the #text HTMLElement is not null or undefined then its parent node should never ever be null or undefined.

本文标签: javascriptwhy is it that text HTMLElement reference to parent Node sometimes return nullStack Overflow