Javascript 使用通配符 ID 选择 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1938294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select div using wildcard ID
提问by Nirmal
How to select a div using it's ID but with a widcard?
如何使用它的 ID 但使用通配符选择一个 div?
If the DIV's ID is statusMessage_1098, I would like to select it in some way like document.getElementById('statusMessage_*').
如果 DIV 的 ID 是statusMessage_1098,我想以某种方式选择它,例如document.getElementById('statusMessage_*').
This is because until the page is generated, I don't know the suffix of the ID and only one such ID will be present in a page. Is this possible?
这是因为在页面生成之前,我不知道 ID 的后缀,并且一个页面中只会出现一个这样的 ID。这可能吗?
Thanks for any help.
谢谢你的帮助。
回答by John K
Wildcard Solution based on element id attribute
基于元素id属性的通配符解决方案
Yes it is possible. This answers your question directly without relying on third-party JavaScript or APIs or attributes other than the id of the element. Also you don't have to use class=
对的,这是可能的。这直接回答了您的问题,而无需依赖第三方 JavaScript 或 API 或元素 id 以外的属性。你也不必使用 class=
Custom Method Call Example
自定义方法调用示例
// Uses JavaScript regex features to search on id= attribute
var arrMatches = document.getElementsByRegex('^statusMessage_.*');
This gets an array containing all elements having an id starting with "statusMessage_" (even nested ones).
这将获取一个包含所有元素的数组,该元素的 id 以“statusMessage_”开头(甚至是嵌套的)。
Implementation Example - reusable and generic
实现示例 - 可重用和通用
Here's an implementation for the getElementsByRegexfunction that searches the DOM for the given regex, starting from document. It's attached to the document object for convenience and according to expected behaviour.
这是getElementsByRegex从document. 为方便起见并根据预期行为,它附加到文档对象。
<head>
<script>
// Called as: document.getElementsByRegex("pattern").
// Returns an array of all elements matching a given regular expression on id.
// 'pattern' argument is a regular expression string.
//
document['getElementsByRegex'] = function(pattern){
var arrElements = []; // to accumulate matching elements
var re = new RegExp(pattern); // the regex to match with
function findRecursively(aNode) { // recursive function to traverse DOM
if (!aNode)
return;
if (aNode.id !== undefined && aNode.id.search(re) != -1)
arrElements.push(aNode); // FOUND ONE!
for (var idx in aNode.childNodes) // search children...
findRecursively(aNode.childNodes[idx]);
};
findRecursively(document); // initiate recursive matching
return arrElements; // return matching elements
};
</script>
</head>
There are likely more efficient implementations but this one provides a start. The body of the function can be replaced with other algorithms according to taste.
可能有更有效的实现,但这提供了一个开始。函数体可以根据喜好替换为其他算法。
Test the Code
测试代码
Finally, test it using an HTML blurb having nested elements like this
最后,使用具有嵌套元素的 HTML 简介来测试它
<body>
<div id="statusMessage_1">1</div>
<div id="statusMessage_2">2
<div id="content">other stuff</div>
<div id="statusMessage_3">3</div>
</div>
<script>
// a quick test to see if you get the expected result.
var arrMatches = document.getElementsByRegex('^statusMessage_.*');
alert('found ' + arrMatches.length + ' matches - expected 3.')
</script>
This HTML block contains three elements starting with id="statusMessage_; therefore the alert test will say
这个 HTML 块包含三个以id="statusMessage_;开头的元素。因此警报测试会说
"found 3 matches - expected 3"
“找到 3 个匹配项 - 预期为 3 个”
Addendum Info for Variations
变体的附录信息
If you want to restrict the search to only div elements or some other kind of specific element then you will want to inject the following getElementByTagNamecode into the algorithm to restrict the set of elements searched against.
如果您想将搜索限制为仅 div 元素或某种其他类型的特定元素,那么您需要将以下getElementByTagName代码注入算法以限制搜索的元素集。
var arrDivs = document.getElementsByTagName("div"); // pull all divs from the doc
You might want to modify the generic algorithm by passing the tag name in a second argument to filter on before searching commences like this
您可能希望通过在第二个参数中传递标签名称以在搜索开始之前进行过滤来修改通用算法,如下所示
var arrMatches = document.getElementsByRegex('^statusMessage_.*', 'div');
回答by rahul
Using jQuery you can do this
使用 jQuery 你可以做到这一点
$("div[id^='statusMessage_']")
Edit - with class name selector
编辑 - 使用类名选择器
If you can use a class name then you can use something like this
如果你可以使用类名,那么你可以使用这样的东西
$$('div.myDivClass');
gets all div elements with class 'myDivClass'
获取所有类 'myDivClass' 的 div 元素
回答by itsvicki
Just thought it was worth updating the thread with a more recent way of doing this in JavaScript as was still coming up in searches.
只是认为值得在 JavaScript 中使用更新的方式更新线程,因为仍在搜索中出现。
document.querySelector("[id^='statusMessage_']");
caniuse.comlists it can be used on IDs from IE8 and great support in other browsers.
caniuse.com列出了它可以用于 IE8 的 ID,并在其他浏览器中提供强大的支持。
回答by jerjer
In jquery, the easiest way is to assign a class for every div let say 'statusMessage' something like:
在 jquery 中,最简单的方法是为每个 div 分配一个类,例如“statusMessage”:
<div id="statusMessage_<%=someid%>" class="statusMessage">...</div>
To get them all:
要全部获得:
$('.statusMessage') // or $('div.statusMessage') //or $('div[id^=statusMessage_]')
Without jquery:
没有jQuery:
var divs = document.getElementsByTagName('div');
for(var i=0;i<divs.length;i++){
if(divs[i].id.indexOf('statusMessage_')==0){
//do stuff here for every divs[i]
}
}
回答by Nicolette Halsema
Update for 2020:
2020 年更新:
Using jQuery you can do this
使用 jQuery 你可以做到这一点
$("div[id^=statusMessage_]")
**Omit the single quotes.
**省略单引号。
I also often add a variable to the end:
我也经常在最后添加一个变量:
$("div[id^=statusMessage_" + id + "]")
回答by bjd223
function switch2 (elementid)
{
var divs = document.getElementsByTagName("div");
for ( var i = 0; divs[i]; i++ )
{
if (divs[i].id.indexOf("statusMessage_") == 0)
{
document.getElementById (divs[i].id).style.display = "none";
}
}
}
Just replace document.getElementById (divs[i].id).style.display = "none";with whatever CSS you want to apply to all divs that have an id that starts with statusMessage_.
只需替换document.getElementById (divs[i].id).style.display = "none";为您想要应用于所有具有以statusMessage_开头的 id 的 div 的 CSS 。
回答by Ramiz Uddin
If you don't want to use jQuery then there is another easier way to do this:
如果您不想使用 jQuery,那么还有另一种更简单的方法来做到这一点:
Assign a class- for an example name it "message", and use the following:
分配一个class- 例如将其命名为“消息”,并使用以下内容:
function getElementsByClass(searchClass,node,tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
Here how you call it:
在这里你如何称呼它:
var messages = getElementsByClass("message");
for(var index=0; index < messages.length; index++) {
// prompt the content of the div
//alert(message[index].innerText);
}
回答by James_2195
I'm not sure how you're populating it but if it's from the code behind you could try something like:
我不确定你是如何填充它的,但如果它来自背后的代码,你可以尝试以下方法:
document.getElementById('statusMessage_<%= generatedID %>')
where generatedID is the ID generated from the code behind.
其中 generateID 是从后面的代码生成的 ID。
回答by Larry K
Usual way to do this within css is to give the elements a class 'statusMessage' in addition to their unique ids. Then you can create a css rule with a selector that will affect all elements with that class. Eg
在 css 中执行此操作的通常方法是为元素提供一个类“statusMessage”以及它们的唯一 id。然后,您可以创建一个带有选择器的 css 规则,该规则将影响具有该类的所有元素。例如
.statusMessage {color: red;}
Remember that elements can have more than one class. Eg
请记住,元素可以有多个类。例如
<p id="id123" class="class1 class2">

