【问题标题】:Select element with specific tag name but with any namespace by using javascript querySelector使用 javascript querySelector 选择具有特定标签名称但具有任何命名空间的元素
【发布时间】:2018-04-13 18:49:47
【问题描述】:

我如何使用 document.querySelector 或 document.querySelectorAll 来获取带有任何 命名空间的特定标签。

我不能使用 JQuery 或任何其他库。

前

<mml:math>
    <mml:row>
    </mml:row>
  </mml:math>
<math style="display:none;">
  <mrow>
   <msup>
     <mfenced>
       <mrow>
         <mi>a</mi>
         <mo>+</mo>
         <mi>b</mi>
       </mrow>
     </mfenced>
     <mn>2</mn>
   </msup>
 </mrow>
</math>

 var tags = ['math:not([style*="display:none"])','mml\\:math:not([style*="display:none"])'];
                              document.querySelectorAll(mathmlVisibleTag.join()).length 

这里用户可以使用任何命名空间。 我在 querySelectorAll 中尝试过'*\\:math:not([style*="display:none"])',但没有成功。

问候

【问题讨论】:

  • 你想选择任何没有没有显示的元素吗?
  • @TKoL 是的。我想找到任何可见的数学元素。

标签: javascript mathml javascript-namespaces


【解决方案1】:

我认为这对于唯一的 querySelectorAll 是不可能的。也许最好的选择是这样的:

function isVisible(e) {
    return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}

var tags = document.querySelectorAll('*'); // change this to be more specific
var visibleMaths = [].slice.call(tags).filter(function (tag) {
    return tag.nodeName.search(/math/i) >= 0 &&
             isVisible(tag);
});

jsfiddle example

【讨论】:

  • Array.from(tags) 不是比[].slice.call(tags) 更可取吗? This resource 说它快得多,但除了更快之外,它在做什么也更明显。
  • 我不知道它是否更快......这真的取决于浏览器。反正我写的是例子,没看细节:)
【解决方案2】:

你只是错过了空间,这个工作正常:

document.querySelectorAll('math :not([style*="display:none"])');

【讨论】:

  • @ePetkvo 以上一个也可以正常工作。我想选择可以有任何命名空间的数学标签。
猜你喜欢
  • 1970-01-01
  • 2010-10-16
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-01
  • 1970-01-01
相关资源
最近更新 更多