如何获得role =“ presentation”元素?

时间:2019-07-06 09:47:29

标签: javascript html

我尝试获取一个元素并对其进行修改。

在开发者控制台中看起来像

document.querySelectorAll('[role="presentation"]').forEach(function(el) {
  console.log('test');
  console.log('innerHTML: ' + el.innerHTML);
});
<div id="toolBarId">
  <table>
    <tbody>
      <tr role="presentation">someElements1</tr>
      <tr>someElements2</tr>
    </tbody>
  </table>
</div>

如果我写的话

document.getElementById('toolBarId').innerHTML;

它打印;

someElements2

我尝试过

document.querySelectorAll('[role="presentation"]').forEach(function (el){
         console.log('test');
//       console.log('innerHTML: ' + el.innerHTML);
         });

它什么也不打印。

编辑: 我在基本html中的“ / body”之前添加了此代码。没有用。

    <script type="text/javascript">

         document.querySelectorAll('[role="presentation"]').forEach(function (el){
             console.log('test');
//           console.log('innerHTML: ' + el.innerHTML);
             });
         </script>
</body>

Edit2:

    if(document.readyState === "complete") {
        testPresentation() ;
        // seems never called
    }
    else {
          window.addEventListener("onload", function () 
                  {testPresentation() ;}, false);
            // seems never called

          //or
          document.addEventListener("DOMContentLoaded", function () {testPresentation() ;}, false);
            // called but selector cannot find first row of the table still
    }

function testPresentation() {

    console.log('testPresentation called');

         document.querySelectorAll('[role="presentation"]').forEach(function (el){
             console.log('test');
//           console.log('innerHTML: ' + el.innerHTML);
             });
}

1 个答案:

答案 0 :(得分:0)

您的表格HTML无效。

tr元素不能有TextNode个子元素。唯一允许的子级是tdth元素(以及scripttemplate)。如果您解决了该问题,它将按预期工作:

document.querySelectorAll('[role="presentation"]').forEach(function(el) {
  console.log('innerHTML: ' + el.innerHTML);
});
<div id="toolBarId">
  <table>
    <tbody>
      <tr>
        <td role="presentation">someElements1</td>
      </tr>
      <tr>
        <td>someElements2</td>
      </tr>
    </tbody>
  </table>
</div>

  

表行<tr>

     

允许的内容:零个或多个<td>和/或<th>元素;脚本支持元素(<script><template>)也被允许

     

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr