getElementByName & Regex

前端 未结 2 1426
盖世英雄少女心
盖世英雄少女心 2021-01-19 17:41

How do I loop through all elements using regular expression in getElementByName?

相关标签:
2条回答
  • 2021-01-19 17:49

    Use a custom selector in jQuery. You probably want an example with parameters.

    0 讨论(0)
  • 2021-01-19 18:05

    If you mean like:

    var elementArray = document.getElementsByName("/regexhere/");
    

    then no that would not be possible.

    To do what you want to do you would have to get all the elements, then go through each one and check the name of it.

    Heres a function that will go through all the elements and add all the elements with a certain name to an array:

        function findElements(name)
        {
            var elArray = [];
            var tmp = document.getElementsByTagName("*");
    
            var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
            for ( var i = 0; i < tmp.length; i++ ) {
    
                if ( regex.test(tmp[i].name) ) {
                    elArray.push(tmp[i]);
                }
            }
    
            return elArray;
    
        }
    

    And use as:

    var elName = "customcontrol";
    
    var elArray = customcontrol(elName);
    

    Or it might be easier by className

        function findElements(className)
        {
            var elArray = [];
            var tmp = document.getElementsByTagName("*");
    
            var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
            for ( var i = 0; i < tmp.length; i++ ) {
    
                if ( regex.test(tmp[i].className) ) {
                    elArray.push(tmp[i]);
                }
            }
    
            return elArray;
    
        }
    

    And use as:

    var elClassName = "classname";
    
    var elArray;
    
    if (!document.getElementsByClassName)
    {
       elArray= findElements(elClassName );
    }
    else
    {
       elArray = document.getElementsByClassName(elClassName);
    }
    

    This would do what you want, without the need for getElementByName.

    Although I think you meant getElementsByName

    If you wanted to look for an element with only the name "customcontrol" you would use:

    var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
    

    If you wanted to look for an element with that STARTED with the name "customcontrol" you would use:

    var regex = new RegExp("(^|\\s)" + name);
    

    EDIT:

    If your using jQuery, which would be easier, then this would do:

    var elArray = $("*[name^='customcontrol']");
    
    //Use JavaScript to loop through
    for (var a = 0; a< elArray.length;a++)
    {
       //Loop through each element
       alert(elArray[a]);
    }
    //Or
    $("*[name^='customcontrol']").css("color","red"); //Or whatever you want to do to the elements
    
    0 讨论(0)
提交回复
热议问题