代码之家  ›  专栏  ›  技术社区  ›  physicsboy

获取组件html中所有可用<button>元素的列表

  •  -2
  • physicsboy  · 技术社区  · 7 年前

    <div>
      <button id="one" #one>one</button>
      <button id="two" #two>two</button>
      <button id="three" #three>three</button>
    </div>
    

    是否可以返回所有按钮的列表?

    constructor() {
      let buttonList = findByElement('button');
    }
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   ellipsis    7 年前

    使用 document.querySelectorAll()

    var div=document.getElementById("div");
    var a=div.querySelectorAll('button');
    console.log(Object.values(a))
    <div id="div">
      <button id="one" #one>one</button>
      <button id="two" #two>two</button>
      <button id="three" #three>three</button>
    </div>
        2
  •  0
  •   OliverRadini    7 年前

    如果你加上 Renderer ElementRef 对于组件,您应该能够访问有问题的元素:

    constructor(private renderer: Renderer, private elem: ElementRef){}
    

    我相信您可以从组件内部调用:

    const elements = this.elem.nativeElement.querySelectorAll('button');
    

    这会给你你所需要的元素。当使用此方法来确保在初始化组件后的某个时刻运行代码时,这一点很重要,而不是像原始代码那样在构造函数中运行,因为我们需要确保我们可以访问该组件的DOM。 This question

    推荐文章