2

たとえば、次の HTML を見ると、要素の子孫のみを無視して、要素のテキスト コンテンツを取得しようとしています。

<p>hello <h1> World </H1> </p>

要素「P」の場合、正しい出力は「hello」のみである必要があります。

関数「element.textContent」を確認しましたが、これはノードとその子孫のテキスト コンテンツを返します (この例では、「hello world」が返されます)。

ありがとう、

4

7 に答える 7

3

この HTML を考慮すると、次のようになります。

<div id="gettext">hello <p> not this </p> world?</div>

「こんにちは」と「世界」を抽出しますか? はいの場合:

var div = document.getElementById('gettext'), // get a reference to the element
    children = [].slice.call(div.childNodes), // get all the child nodes
                                              // and convert them to a real array  
    text = children.filter(function(node){
        return node.nodeType === 3;           // filter-out non-text nodes
    })
    .map(function( t ){ 
        return t.nodeValue;                   // convert nodes to strings 
    });    

console.log( text.join('') );                 // text is an array of strings.

http://jsfiddle.net/U7dcw/

于 2013-09-20T10:14:07.893 に答える
1

その後ろには説明があります

 $("p").clone()   //clone element
        .children() //get all child elements
        .remove()   //remove all child elements
        .end()  //get back to the parent
        .text();
于 2013-09-20T10:04:40.767 に答える
1

私が持っている答えは、他のいくつかの答えで提供されているものと同じです。ただし、説明を試みます。

<p >hello<h1>World</h1> </p>

この行は次のようにレンダリングされます

こんにちは

世界

このコードを見ると、次のようになります

<p>hello</p>
<h1>World</h1> 
<p></p>

タグを使用すると、段落の後に要素が続く場合、 <p>必ずしも終了タグは必要ありません。この記事をチェック</p>

次のコードを使用するだけで、最初の p タグのコンテンツを選択できるようになりました。

var p = document.getElementsByTagName('p');
console.log(p[0].textContent);

JSフィドル

于 2013-09-20T10:19:31.253 に答える
0

それを使って何らかの操作を行いたい要素にIDを提供してみてください。

Below is the working example, it show output as "hello" as you expected.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showParagraph()
{
   alert(document.getElementById('test').innerHTML);

}
</script>
</head>

<body>
<p id="test">hello <h1> World </H1> </p>
<input type="button" onclick="showParagraph()" value="show paragraph" />
</body>

</html>
于 2013-09-20T10:10:29.930 に答える
0

childNodesプロパティを使用できます。つまり、次のようになります。

var p = document.querySelector('p');
p.childNodes[0]; // => hello

jsフィドル

于 2013-09-20T10:04:26.757 に答える
0

あなたのhtmlをに変更してください

<p id="id1">hello <h1> World </h1> </p>

このスクリプトを使用して、

alert(document.getElementById("id1").firstChild.nodeValue);
于 2013-09-20T10:08:11.110 に答える
0

プレーン テキストは、 という名前のノードと見なされ#textます。childNodes要素のプロパティを使用して、その中の各項目pのプロパティを確認できます。nodeNameそれらを繰り返し処理して、#textノードだけを選択できます。

以下の関数は、ドキュメント内のすべての要素をループし、#textアイテムだけを出力します

function myFunction()
{
    var txt="";
    var c=document.body.childNodes;
    for (i=0; i<c.length; i++)
    {
        if(c[i].nodeName == "#text")
            txt=txt + c[i].nodeName + "<br>";
    };
    return txt;
}

編集:

@VisioN がコメントで述べたように、nodeType(ブラウザの互換性のために) を使用する方がはるかに安全であり、推奨されます。

于 2013-09-20T10:06:43.920 に答える