0

this is my first come here ask questions.

this my code

let nb: Element;
    if (sc.hasChildNodes() == true) {
        let lc = sc.lastChild!;
        lc.insertBefore(newButton, lc);
        nb = sc.lastChild!;
    }

get error : Type 'ChildNode' is missing the following properties from type 'Element': attributes, classList, className, clientHeight, and 106 more.

---------- Update ----------

just need to know what is " Type Assertions "

this update code

let nb: Element;
    if (sc.hasChildNodes() == true) {
        sc.lastChild!.after(newButton);
        nb = sc.lastChild! as Element;
    }

1 Answers1

0

you don't need all those conditions - you just need to know if you want to use lastElementChild or lastChild in the following code:

const insertButtonBeforeLastChild = (sc, btn) => sc.lastElementChild && sc.insertBefore(btn, sc.lastElementChild);

insertButtonBeforeLastChild(sc1, document.createElement('button'));
insertButtonBeforeLastChild(sc2, document.createElement('button'));
insertButtonBeforeLastChild(sc3, document.createElement('button'));
insertButtonBeforeLastChild(sc4, document.createElement('button'));
insertButtonBeforeLastChild(sc5, document.createElement('button'));
div, button{min-height:1em;margin:5px;display:block;border:1px dotted blue;}
div div{background:#CCC;}
<div id="sc1"></div>
<div id="sc2">text</div>
<div id="sc3"><div>onlychild</div></div>
<div id="sc4"><div>first</div><div>second</div></div>
<div id="sc5"><div>first</div><div>second</div>third-text</div>

In regards to the question you can generally use MyNode as Element to specify the specific type in TS. But your updated code looks like you are trying to do something like this:

let nb: Element | null = sc.lastChild ? sc.appendChild(newButton) : null;
Ian Carter
  • 548
  • 8
  • 7
  • my problem actually not complicated , really just add "as" can be solved , but your grammar more concise , i can learn , thank you help . – Kaosu-Niku Oct 16 '22 at 03:28