[英]Get the value of an <h2> tag with JavaScript
我正在嘗試生成具有<h2>
標記的頁面上每個元素的MD5校驗和,然后將值顯示為彈出窗口。
我已經得到的每個<h2>
元素的代碼,我只需要得到每個元素的實際值。
var ghead = document.getElementsByTagName('h2');
for (i=0; i<ghead.length; i++) {
var gh = ghead[i];
var ts = gh.toString();
var ms = b64_md5(ts);
alert(ts);
alert(ms);
}
b64_md5(ts)
的用法基本上是將ts
變量轉換為MD5值。 但是, ts
變量是Element類型的ID或名稱,而不是Element的值本身。
另外,如果我想創建一個存儲有兩個值的cookie,一個名稱和一個校驗和,我可以使用gh.innerText;
設置唯一名稱,因為到目前為止我遇到了使用此方法的問題。
您可以使用innerHTML
屬性來獲取元素的HTML內容:
var ts = gh.innerHTML;
請注意, h2
元素(以及大多數其他元素)沒有“值”。 只有表現為表單控件的元素才具有value
屬性(例如input
元素)。
如果要訪問元素的類型,可以直接詢問:
gh.nodeName // contains the name of the node in uppercase e.g. "H2"
gh.nodeType // contains the numerical Type of the node e.g. "1"
gh.id // contains the value of the node's id attribute
gh.name // contains the value of the name attribute (typically for form elements)
如下所述,訪問實際節點內容是另一回事:
gh.innerHTML // contains the full html source within the node
gh.innerText // (IE only) contains the visible textual content stripped of any html markup
gh.textContent // W3C compliant equivalent of innerText
對於跨瀏覽器訪問文本內容,請使用以下內容:
var text = gh.innerText || gh.textContent;
要獲取h2標記元素的文本內容gh:
var text = gh.childNodes.item(0).data;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.