skip to Main Content

i want to find and hide button "Add" in typescript.
How to do it ?

<div class="edittoolbar">
  <div class="btn-group" role="group">
    <button class="btn btn-primary" title="Add">
    </button>
    <button class="btn btn-primary" title="Modify">
    </button>
    <button class="btn btn-primary" title="Delete">
    </button>
  </div>
</div>

i using this code to find button but it not success.
because myNodeList1.length is return =0 , so i can not continue to find it.
please help me. Thank you!

const nodes = document.querySelectorAll('div.edittoolbar div.btn-group') ;
console.log(nodes);

const myNodeList1: NodeListOf<Element> = nodes.item(0).childNodes ;  // node
console.log(myNodeList1.length) ;

enter image description here

i expecting have a ways to do it.

3

Answers


  1. querySelector() returns the first Element

    const nodes = document.querySelector(".btn.btn-primary")
    

    childNodes returns all child nodes, including text nodes (including spaces and line breaks) and comment nodes. this can lead to unexpected results, so be careful.

    if you need purely element nodes, the children property is more appropriate.

    const nodes = document.querySelectorAll("div.edittoolbar div.btn-group");
    const myNodeList1 = nodes.item(0).children; // childNodes => children
    
    Login or Signup to reply.
  2. to access array elements by index you have to use []<‘square brackets’> , here you are using ()<‘parenthesis’>;

    right way

    const myNodeList1: NodeListOf<Element> = nodes.item[0].childNodes ;  // node
    console.log(myNodeList1.length) ;
    

    change

    item(0) --> item[0]
    
    Login or Signup to reply.
  3. I cannot reproduce your results.
    Your code gives the following compile error:

    Type ‘NodeListOf<ChildNode>’ is not assignable to type
    ‘NodeListOf<Element>’.

    I have tried this:

    const nodes = document.querySelectorAll("div.btn-group")
    const myNodeList1: NodeListOf<ChildNode> = nodes[0].childNodes
    console.log(myNodeList1)
    console.log(myNodeList1.length)
    

    and the result is 7. Button ‘Add’ is myNodeList1[1].

    A simple way to find the button with title="Add" is:

    const node: HTMLButtonElement | null = document.querySelector('button[title="Add"]')
    

    If you still have a problem, please share a complete, but small working application.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search