Select tags that starts with “x-” in jQuery

2020-03-13 04:26发布

How can I select nodes that begin with a "x-" tag name, here is an hierarchy DOM tree example:

<div>
  <x-tab>
    <div></div>
    <div>
      <x-map></x-map>
    </div>
  </x-tab>
</div>
<x-footer></x-footer>

jQuery does not allow me to query $('x-*'), is there any way that I could achieve this?

9条回答
Deceive 欺骗
2楼-- · 2020-03-13 04:50

custom jquery selector

jQuery(function($) {
    $.extend($.expr[':'], {
        X : function(e) {
            return /^x-/i.test(e.tagName);
        }
    });
});

than, use $(":X") or $("*:X") to select your nodes.

查看更多
在下西门庆
3楼-- · 2020-03-13 04:54

It might not be efficient, but consider it as a last option if you do not get any answer.
Try adding a custom attribute to these tags. What i mean is when you add a tag for eg. <x-tag>, add a custom attribute with it and assign it the same value as the tag, so the html looks like <x-tag CustAttr="x-tag">.
Now to get tags starting with x-, you can use the following jQuery code:

$("[CustAttr^=x-]")

and you will get all the tags that start with x-

查看更多
淡お忘
4楼-- · 2020-03-13 04:55

See if this works!

function getXNodes() {
  var regex = /x-/, i = 0, totalnodes = [];
  while (i !== document.all.length) {
    if (regex.test(document.all[i].nodeName)) {
      totalnodes.push(document.all[i]);
    }
    i++;
  }
  return totalnodes;
}
查看更多
登录 后发表回答