我正试图从一段HTML代码(不是我的)获取字符串:THIS is what I need
<div class="hlFld-Abstract"><h2 id="section-1"><span>Abstract</span></h2><div class="abstractSection abstractInFull"><p xmlns:mml="http://www.w3.org/1998/Math/MathML">THIS is what I need</p> </div></div><h2><span>Keywords</span>
为此,我写了以下内容:
document.getElementById("section-1").document.getElementsByClassName("abstractSection abstractInFull")[0].textContent
它几乎完成了这项工作,但它也包括▪ Abstract
,我不需要它。如何只获取字符串THIS is what I need
?
答案 0 :(得分:2)
您可以使用querySelector
:
console.log(document.querySelector('div.abstractSection.abstractInFull p').textContent)
&#13;
<div class="hlFld-Abstract"><h2 id="section-1"><span>Abstract</span></h2><div class="abstractSection abstractInFull"><p xmlns:mml="http://www.w3.org/1998/Math/MathML">THIS is what I need</p> </div></div><h2><span>Keywords</span>
&#13;
答案 1 :(得分:2)
以下是纯Javascript的快速解决方案:
querySelector
var mytext = document.querySelector("div[class='abstractSection abstractInFull']");
alert(mytext.textContent);
&#13;
<div class="hlFld-Abstract"><h2 id="section-1"><span>Abstract</span></h2><div class="abstractSection abstractInFull"><p xmlns:mml="http://www.w3.org/1998/Math/MathML">THIS is what I need</p></div></div><h2><span>Keywords</span>
&#13;
现在这里是jQuery的快速解决方案
$(document).ready(function () {
var myText = $("div[class='abstractSection abstractInFull']").text();
alert(myText);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="hlFld-Abstract"><h2 id="section-1"><span>Abstract</span></h2><div class="abstractSection abstractInFull"><p xmlns:mml="http://www.w3.org/1998/Math/MathML">THIS is what I need</p></div></div><h2><span>Keywords</span>
&#13;
答案 2 :(得分:1)
试试这样。使用document.querySelector()
。
var text = document.querySelector('p');
alert(text.textContent);
&#13;
<div class="hlFld-Abstract"><h2 id="section-1"><span>Abstract</span></h2><div class="abstractSection abstractInFull"><p xmlns:mml="http://www.w3.org/1998/Math/MathML">THIS is what I need</p> </div></div><h2><span>Keywords</span>
&#13;
答案 3 :(得分:-2)
使用Query Selector或Jquery链接。我看到你的html DOM似乎不正确。