Select div using wildcard ID

前端 未结 9 1777
旧时难觅i
旧时难觅i 2020-11-29 11:30

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

9条回答
  •  盖世英雄少女心
    2020-11-29 12:04

    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.

    
    
    
    

    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

    
    
    
    1
    2
    other stuff
    3

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

提交回复
热议问题