使用通配符ID选择div

Nir*_*mal 6 javascript jquery dom prototypejs

如何使用它的ID但使用widcard选择div?

如果是DIV的ID statusMessage_1098,我想以某种方式选择它document.getElementById('statusMessage_*').

这是因为在生成页面之前,我不知道ID的后缀,并且页面中只会出现一个这样的ID.这可能吗?

谢谢你的帮助.

Joh*_*n K 19

基于元素id属性的通配符解决方案

对的,这是可能的.这将直接回答您的问题,而不依赖于第三方JavaScript或API或元素ID以外的属性.你也不必使用class =

自定义方法调用示例

// Uses JavaScript regex features to search on id= attribute
var arrMatches = document.getElementsByRegex('^statusMessage_.*');
Run Code Online (Sandbox Code Playgroud)

这将获得一个数组,其中包含所有id为"statusMessage_"(甚至是嵌套的)的元素.

实现示例 - 可重用和通用

这是一个getElementsByRegex函数的实现,它从DOM开始搜索给定的正则表达式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>
Run Code Online (Sandbox Code Playgroud)

可能会有更高效的实现,但这个实现提供了一个开始.功能的主体可以根据品味用其他算法替换.

测试代码

最后,使用具有此类嵌套元素的HTML blurb对其进行测试

<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>
Run Code Online (Sandbox Code Playgroud)

此HTML块包含三个以id="statusMessage_; 开头的元素; 因此警报测试会说

"找到3场比赛 - 预计3"

变异的附录信息

如果要将搜索限制为仅div元素或其他某种特定元素,则需要将以下getElementByTagName代码注入算法以限制搜索的元素集.

var arrDivs = document.getElementsByTagName("div"); // pull all divs from the doc
Run Code Online (Sandbox Code Playgroud)

您可能希望通过在第二个参数中传递标记名称来修改通用算法,以便在搜索开始之前进行过滤

var arrMatches = document.getElementsByRegex('^statusMessage_.*', 'div');
Run Code Online (Sandbox Code Playgroud)


rah*_*hul 12

使用jQuery你可以做到这一点

$("div[id^='statusMessage_']")
Run Code Online (Sandbox Code Playgroud)

请参见attributeStartsWith

编辑 - 使用类名选择器

如果你可以使用类名,那么你可以使用这样的东西

$$('div.myDivClass');
Run Code Online (Sandbox Code Playgroud)

使用类'myDivClass'获取所有div元素

  • Prototype支持相同的选择器,只需使用$$:http://www.prototypejs.org/api/utility/dollar-dollar (3认同)
  • 为了说明这一点,要执行OP在Prototype中的要求,命令是:$$(“ div [id ^ ='statusMessage_']”) (2认同)

小智 10

只是认为值得用更新的方式在JavaScript中更新线程,因为搜索仍在进行中.

document.querySelector("[id^='statusMessage_']");
Run Code Online (Sandbox Code Playgroud)

caniuse.com列出它可用于IE8的ID和其他浏览器的强大支持.

  • 感谢您的回答。如果需要获取多个元素,可以使用`document.querySelectorAll()`。 (2认同)