如何按类获取以前的相邻元素?

时间:2016-12-05 04:51:52

标签: javascript

页面中有几个article-text的元素,但我想抓住位于共享按钮上方的元素。 html看起来像这样:

<div class="article-text">
 This is not intended to be grabbed
</div>

<div class="article-text">
  Text to be grabed
</div>

<a href="https://twitter.com/intent/tweet?source=http%3A%2F%2Fmysite.com&text=:%20http%3A%2F%2Fmysite.com&via=mySite" target="_blank" title="Tweet" onclick="window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(document.title) + ':%20'  + encodeURIComponent(document.URL) + ' ' +encodeURIComponent(document.getElementsByClassName('article-text').previousSibling)); return false;">

<div class="article-text">
 This is not intended to be grabbed
</div>

这会返回undefined。我也试过了document.getElementsByClassName('article-text')[0]但是抓住了页面网址。所以我一无所知,感谢你的帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用this.previousElementSibling.textContent.trim()

encodeURIComponent(this.previousElementSibling.textContent.trim())

&#13;
&#13;
<div class="article-text">
 This is not intended to be grabbed
</div>

<div class="article-text">
  Text to be grabed
</div>

<a href="#" target="_blank" title="Tweet" onclick="console.log(this.previousElementSibling.textContent.trim())">

<div class="article-text">
 This is not intended to be grabbed
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

&#13;
&#13;
window.onload = function(e){ 
    var shareBtn = document.getElementById("share").previousSibling;
    console.log(shareBtn)
    
}
&#13;
<div class="article-text">
 This is not intended to be grabbed
</div>

<div class="article-text">
  Text to be grabed
</div>

    <a id='share' href="https://twitter.com/intent/tweet?source=http%3A%2F%2Fmysite.com&text=:%20http%3A%2F%2Fmysite.com&via=mySite" target="_blank" title="Tweet" onclick="window.open('https://twitter.com/intent/tweet?text=' + encodeURIComponent(document.title) + ':%20'  + encodeURIComponent(document.URL) + ' ' +encodeURIComponent(document.getElementsByClassName('article-text').previousSibling)); return false;">

<div class="article-text">
 This is not intended to be grabbed
</div>
&#13;
&#13;
&#13;