使用JavaScript </h2>获取<h2>标记的值

时间:2012-07-03 12:35:09

标签: javascript html html-heading

我正在尝试生成具有<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变量是元素类型的ID或名称,而不是元素的值本身。

另外,如果我想创建一个存储有两个值的cookie,一个名称和一个校验和,我可以使用gh.innerText;来设置唯一名称,因为我在使用这个方法时遇到了问题所以远。

3 个答案:

答案 0 :(得分:11)

您可以使用innerHTML属性来获取元素的HTML内容:

var ts = gh.innerHTML;

请注意,h2元素(以及大多数其他元素)没有“值”。只有表现为表单控件的元素才具有value属性(例如input元素)。

答案 1 :(得分:1)

如果您想访问元素的类型,您可以直接询问:

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;

答案 2 :(得分:1)

获取h2标签元素的文本内容gh:

var text = gh.childNodes.item(0).data;
相关问题