2011-10-05 16 views
0

所以,假設我有一個非常基本的頁面,其中包含正文,單個div和段落元素以及一些文本。文本節點的「nodeValue」屬性爲空 - 那麼我該如何測試它呢?

<body> 
    <div> 
    <p>some text</p> 
    <div> 
</body> 

根據瀏覽器上,主體/ div元素將具有文本節點(節點類型=== 3的nodeValue === 「--blank--」)。然而,P元素將有一個合法的文本節點和nodeValue ===「一些文本」。

我想知道的是,代表空格的'假'文本節點的「nodeValue」(--blank--)是什麼,因爲我想寫一個if測試,可以讓我過濾掉假文本節點。

例子:

var body = document.getElementsByTagName("body")[0]; // shortcut to body element. 
console.log(body.childNodes[0].nodeValue) // maps to one of the fake text nodes that are blank. 
// returns a blank line. What is that "blank" equal to? It's not 'null' or "" or undefined... 

乾杯, 亞歷

+2

訪問身體的最快方式是* document *的* body *屬性,即[document.body](http://www.w3.org/TR/DOM-Level-2-HTML/)中將Html.HTML#ID-56360201)。 – RobG

回答

1

只是trim()[docs]的空白,並看看有沒有什麼事:

if(body.childNodes[0].nodeValue.trim()) { 
    // more than white space 
} else { 
    // just white space 
} 

如果只有白色的空間,你會最終得到一個虛假的價值。否則它會是真的。

該文檔的鏈接提供以下兼容性墊片:

if (!String.prototype.trim) { 
    String.prototype.trim = function() { 
     return this.replace(/^\s+|\s+$/g, ''); 
    }; 
} 
2

你可以使用正則表達式,如:

var re = /\S/; // Match non-whitespace 
if (node.nodeType == 3 && re.test(node.nodeValue)) { 
    // text node has something other than whitespace 
} 

提的是,有什麼瀏覽器要考慮空白,什麼是輕微的變化匹配\s,但這可能並不重要。

相關問題