たとえば、次の HTML を見ると、要素の子孫のみを無視して、要素のテキスト コンテンツを取得しようとしています。
<p>hello <h1> World </H1> </p>
要素「P」の場合、正しい出力は「hello」のみである必要があります。
関数「element.textContent」を確認しましたが、これはノードとその子孫のテキスト コンテンツを返します (この例では、「hello world」が返されます)。
ありがとう、
たとえば、次の HTML を見ると、要素の子孫のみを無視して、要素のテキスト コンテンツを取得しようとしています。
<p>hello <h1> World </H1> </p>
要素「P」の場合、正しい出力は「hello」のみである必要があります。
関数「element.textContent」を確認しましたが、これはノードとその子孫のテキスト コンテンツを返します (この例では、「hello world」が返されます)。
ありがとう、
この 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.
その後ろには説明があります
$("p").clone() //clone element
.children() //get all child elements
.remove() //remove all child elements
.end() //get back to the parent
.text();
私が持っている答えは、他のいくつかの答えで提供されているものと同じです。ただし、説明を試みます。
<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);
それを使って何らかの操作を行いたい要素に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>
childNodes
プロパティを使用できます。つまり、次のようになります。
var p = document.querySelector('p');
p.childNodes[0]; // => hello
あなたのhtmlをに変更してください
<p id="id1">hello <h1> World </h1> </p>
このスクリプトを使用して、
alert(document.getElementById("id1").firstChild.nodeValue);
プレーン テキストは、 という名前のノードと見なされ#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
(ブラウザの互換性のために) を使用する方がはるかに安全であり、推奨されます。