Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

javascript - Select div using wildcard ID

How to select a div using it's ID but with a widcard?

If the DIV's ID is statusMessage_1098, I would like to select it in some way like 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?

Thanks for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Wildcard Solution based on element id attribute

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=

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).

Implementation Example - reusable and generic

Here's an implementation for the getElementsByRegex function 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.

<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

<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

"found 3 matches - expected 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 getElementByTagName code into the algorithm to restrict the set of elements searched against.

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...