【问题标题】:How to get role="presentation" elements?如何获取 role="presentation" 元素?
【发布时间】:2019-11-16 16:07:23
【问题描述】:

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

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

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>

编辑2:

    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);
             });
}

【问题讨论】:

  • 那会是什么问题呢?也许生成表的 js 代码在我的查询选择器之后运行?但是我也不会得到第二排。
  • 从第一条语句的打印结果来看,当该语句运行时,第一行似乎不存在(具有role 属性的行)。看起来#toolBarId div 不包含表格,它只有以下文本:someElements2
  • 我可以安排一些优先级查询选择器将是代码最终运行吗?谢谢
  • 是的,在生成表格的函数完成后调用。

标签: javascript html


【解决方案1】:

您的表格 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>

表格行&lt;tr&gt;

允许的内容:零个或多个 &lt;td&gt; 和/或 &lt;th&gt; 元素;还允许支持脚本的元素(&lt;script&gt;&lt;template&gt;

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

【讨论】:

  • tr 元素中有 td
  • @classeswilldullyourmind 不在您在问题中显示的 HTML 中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2013-06-13
  • 2020-10-30
  • 1970-01-01
  • 2020-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多