getElementsByName:按最后部分名称控制
我可以通过id获取div元素并仅使用部分名称“first”
HTML
first.1.end first.2.end two.3.end first.4.end
JS
function getElementsByIdStartsWith(selectorTag, prefix) { var items = []; var myPosts = document.getElementsByTagName(selectorTag); for (var i = 0; i < myPosts.length; i++) { if (myPosts[i].id.lastIndexOf(prefix, 0) === 0) { items.push(myPosts[i]); } } return items; } var postedOnes = getElementsByIdStartsWith("div", "first"); alert(postedOnes.length);
它计算3个div元素(警报)。
但是如何使用末端部分名称进行搜索? 例如使用“结束”?
来自MDN属性选择器 :
[attr ^ = value]表示属性名称为attr且其值以“value”为前缀的元素。
[attr $ = value]表示属性名称为attr且其值以“value”为后缀的元素。
因此,您可以使用[id^="first"]
查找id以"first"
开头的元素。 并使用[id$="end"]
查找以"end"
元素。
喜欢
// This find all div which id ends with "end". var divs = document.querySelectorAll('div[id$="end"]');
或者使用jQuery:
$('div[id$="end"]');
此外,您可以将多个属性选择器组合在一起以查找更具体的元素:
// As we only use querySelector, it find the first div with id starts with "two" and ends with "end". var divStartAndEnd = document.querySelector('div[id^="two"][id$="end"]');
请参阅jsfiddle上的演示
在这里,我允许用户传递所有三个参数。 假设用户没有通过midmatch,那么它将仅返回第一个和最后一个匹配。
以下是工作代码:
它将返回1个计数:
function getElementsByIdStartsWith(selectorTag, firstmatch, midmatch, lastmatch) { var items = []; var myPosts = document.getElementsByTagName(selectorTag); for (var i = 0; i < myPosts.length; i++) { var firstmatchIndex = firstmatch?myPosts[i].id.indexOf(firstmatch)>-1?true : false : true; var midmatchIndex = midmatch?myPosts[i].id.indexOf(midmatch)>-1?true : false : true; var lastmatchIndex = lastmatch?myPosts[i].id.indexOf(lastmatch)>-1?true : false : true; if (firstmatchIndex && midmatchIndex && lastmatchIndex ) { items.push(myPosts[i]); } } return items; } var postedOnes = getElementsByIdStartsWith("div", "first", "2", "end"); alert(postedOnes.length); // now it will show only one in alert.
它会返回3个计数:
function getElementsByIdStartsWith(selectorTag, firstmatch, midmatch, lastmatch) { var items = []; var myPosts = document.getElementsByTagName(selectorTag); for (var i = 0; i < myPosts.length; i++) { var firstmatchIndex = firstmatch?myPosts[i].id.indexOf(firstmatch)>-1?true : false : true; var midmatchIndex = midmatch?myPosts[i].id.indexOf(midmatch)>-1?true : false : true; var lastmatchIndex = lastmatch?myPosts[i].id.indexOf(lastmatch)>-1?true : false : true; if (firstmatchIndex && midmatchIndex && lastmatchIndex ) { items.push(myPosts[i]); } } return items; } var postedOnes = getElementsByIdStartsWith("div", "first", "", "end"); alert(postedOnes.length); // now it will show only three in alert.
如果你不想考虑任何参数,只需在调用函数时传递空字符串( “” )。
希望对你有帮助 :)
我想通过使用jQuery + regex可以实现这种选择。 看看这个
如何使用正则表达式使用jQuery通过ID选择元素?
可能是你想要的线上的一些东西。