Javascript getElementsByClass HTML

时间:2013-03-25 20:02:43

标签: javascript html

我遇到问题使用简单的'getElementsByClass'函数循环遍历表单上的元素。我必须使用这个标题:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

我还必须使用IE8。

如果我删除标题,该功能正常。我意识到错误的标签不在正确的位置,但如果我删除它们,该功能也能正常工作。页面还有更多内容,但这里有一个精简版本:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script type="text/javascript">
    function getElementsByClass(node,searchClass,tag) {    
        var classElements = new Array();
        var els = node.getElementsByTagName(tag); // use "*" for all elements
        var elsLen = els.length;
            alert("elsLen: " + elsLen);        
        var pattern = new RegExp("\\b"+searchClass+"\\b");
        for (i = 0, j = 0; i < elsLen; i++) {          
         if ( pattern.test(els[i].className) ) {
     classElements[j] = els[i];
     j++;
     }
    }
    alert("getElementsByClass: classElements.length: " + classElements.length);
    return classElements;
    }
</script>
</head>
<body>
<table>
  <form name="formOne"> 
      <input type="button" value="click" onclick="getElementsByClass(document.formOne,'popupElement','*');" />          
      <input type="text" class="popupElement">
   </form>        

  <form name="formTwo"> 
        <table>                
        <input type="text"  class="popupElement">
        <input type="text" class="popupElement"> 
        <input type="button" value="click2" onclick="getElementsByClass(document.formTwo,'popupElement','*');" />
  </form>

第一次调用formOne上的getElementsByClass()会正确触发并在警告框中显示正确的值。但是在formTwo上调用时,该函数在表单上找不到任何元素。

我只想弄清楚为什么会发生这种情况所以我可以开发出一种解决方法。

1 个答案:

答案 0 :(得分:0)

首先,我无法在IE8上复制它,这似乎是IE9的一个问题。

问题在于您提供的HTML。 IE DOM解析器由于某种原因在最终标签的位置混淆,因此正在创建空标签(&lt;&gt;)。在您的情况下,表单最终是一个空标记,导致以下输出。

LOG: elsLen: 0 
LOG: getElementsByClass: classElements.length: 0 

尝试使用此标记。

<html>
<body>
<table>
<tbody>
    <tr>
        <td>
            <form name="formOne"> 
                <input type="button" value="click" onclick="getElementsByClass(document.formOne,'popupElement','*');" />          
                <input type="text" class="popupElement" />
            </form> 
        </td>
    </tr>
    <tr>
        <td>
            <form name="formTwo"> 
                <table>
                    <tbody>
                        <tr>
                            <td>
                                <input type="text"  class="popupElement"/>
                                <input type="text" class="popupElement"/> 
                                <input type="button" value="click2" onclick="getElementsByClass(document.formTwo,'popupElement','*');" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </form>
        </td>
    </tr>
</tbody>
</table>
</body>
</html>

主要是我关闭了所有标签并跟随HTML 4.01 table schema