簡體   English   中英

如何使用 JavaScript 在 div 中抓取文本?

[英]How to grab a text inside a div using JavaScript?

我正在嘗試使用 JS 獲取#address div 中的文本。 出於某種原因,我不斷得到一個null值。 如果我做了我不應該做的事情,請糾正我。 這是我嘗試過的:

 function myFunction() { var uri = "www. google.com"; var res = encodeURIComponent(uri); var address = document.getElementById("address"); console.log(uri); // print out = www. google.com console.log(res); // print out = www.%20google.com console.log(address); // print out = null ???? }
 <script src="//code.jquery.com/jquery-1.10.2.js"></script> <div id="address"> 410 Walker Street Lowell MA 01851</div> <h1>console.log();</h1> <button onclick="myFunction()">Run</button>

您正在獲取 DOMElement,但沒有從中檢索文本。 要做到這一點,請使用innerText 嘗試這個:

 function myFunction() { var uri = "www. google.com"; var res = encodeURIComponent(uri); var address = document.getElementById("address").innerText; // note innerText here console.log(uri); // print out = www. google.com console.log(res); // print out = www.%20google.com console.log(address); // print out = null ???? }
 <script src="//code.jquery.com/jquery-1.10.2.js"></script> <div id="address"> 410 Walker Street Lowell MA 01851</div> <h1>console.log();</h1> <button onclick="myFunction()">Run</button>

或者,正如您已經用 jQuery 標記了這個問題:

var address = $('#address').text();

另請注意,您在 HTML 中設置了id="addess" ,這似乎是一個錯字。

做這個:

var address = document.getElementById("address").innerHTML;

如果您使用的是 jquery,那么呢?

$("#address").html()

編輯:您需要包含 jquery 才能在您的標簽中工作。

如果您導入 jquery 庫,您可以執行以下操作:

$('#address').text();  //get's the text
$('#address').text("some text"); //sets the text

$('#address').text("some text"+ $('#address').text());  //prepends

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM