通过ClassName获取元素而不在<span>中使用字符串

时间:2017-01-21 02:06:41

标签: javascript html

我正试图从一段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

4 个答案:

答案 0 :(得分:2)

您可以使用querySelector

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:2)

以下是纯Javascript的快速解决方案:

  

querySelector

&#13;
&#13;
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;
&#13;
&#13;

现在这里是jQuery的快速解决方案

&#13;
&#13;
$(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;
&#13;
&#13;

答案 2 :(得分:1)

试试这样。使用document.querySelector()

&#13;
&#13;
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;
&#13;
&#13;

答案 3 :(得分:-2)

使用Query Selector或Jquery链接。我看到你的html DOM似乎不正确。