getElementByName&正则表达式 [英] getElementByName & Regex

查看:69
本文介绍了getElementByName&正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用getElementByName中的正则表达式遍历所有元素?

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

推荐答案

如果您的意思是:

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;

    }

并用作:

var elName = "customcontrol";

var elArray = customcontrol(elName);

或者className可能更容易

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;

    }

并用作:

var elClassName = "classname";

var elArray;

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

这可以做你想要的,而不需要getElementByName。

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

虽然我认为你的意思是getElementsByName

Although I think you meant getElementsByName

如果你想找一个只有名字customcontrol的元素你会使用:

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

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

如果您想查找名称为customcontrol的STARTED元素,您可以使用:

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

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

编辑:

如果你使用jQuery ,这会更容易,然后这样做:

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

这篇关于getElementByName&amp;正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆