查找所有ID以公共字符串开头的元素
问题描述:
我有一个XSL,它创建了ID为"createdOn"和$ unique-id的多个元素
I have a XSL that created multiple elements with the id of "createdOn" plus a $unique-id
Example : createdOnid0xfff5db30
我想使用JavaScript查找并将它们存储在变量中.我已经尝试过
I want to find and store these in a variable using JavaScript. I've tried
var dates = document.getElementsById(/createdOn/);
但这似乎不起作用.
答
Using jQuery you can use the attr starts with selector:
var dates = $('[id^="createdOnid"]');
使用现代浏览器,您可以使用 CSS3属性值始于选择器以及 querySelectorAll
:
Using modern browsers, you can use the CSS3 attribute value begins with selector along with querySelectorAll
:
var dates = document.querySelectorAll('*[id^="createdOnID"]');
但是要回退旧版浏览器(且不使用jQuery),您需要:
But for a fallback for old browsers (and without jQuery) you'll need:
var dateRE = /^createdOnid/;
var dates=[],els=document.getElementsByTagName('*');
for (var i=els.length;i--;) if (dateRE.test(els[i].id]) dates.push(els[i]);