Prototype - cleanWhitespace() 方法

此方法删除元素的所有文本节点(仅包含空格)并返回元素。

Element.cleanWhitespace 删除仅包含空格的文本节点。当使用 nextSibling、previousSibling、firstChildlastChild 等标准方法遍历 DOM 时,这非常有用。

语法

element.cleanWhitespace();

返回值

HTML 元素

示例

请考虑以下示例 −

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showElements() {
            var element = $('apples');
            alert(element.firstChild.innerHTML);
         }
      </script>
   </head>
   
   <body>
      <ul id = "apples">
         <li>Mutsu</li>
         <li>McIntosh</li>
         <li>Ida Red</li>
      </ul>
      <br />
      
      <input type = "button" value = "showElements" onclick = "showElements();"/>
   </body>
</html>

这似乎不太管用。为什么会这样?ul#apples 的第一个子节点实际上是一个文本节点,仅包含位于 <ul id = "apples"> 和 <li>Mutsu</li> 之间的空格。

输出

现在,让我们使用 cleanWhitespace 函数并查看结果 −

<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showElements() {
            var element = $('apples');
            element.cleanWhitespace();
            alert(element.firstChild.innerHTML);
         }
      </script>
   </head>

   <body>
      <ul id = "apples">
         <li>Mutsu</li>
         <li>McIntosh</li>
         <li>Ida Red</li>
      </ul>
      <br />
      
      <input type = "button" value = "showElements" onclick = "showElements();"/>
   </body>
</html>

输出

prototype_element_object.html