简体   繁体   English

获得一个的价值 <h2> 用JavaScript标记

[英]Get the value of an <h2> tag with JavaScript

I am trying to generate an MD5 check-sum of every element on a page that has the <h2> tag, then display the values as a popup. 我正在尝试生成具有<h2>标记的页面上每个元素的MD5校验和,然后将值显示为弹出窗口。

The code I have already should get each <h2> element, I just need to get the actual value of each one. 我已经得到的每个<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);
}

The usage of b64_md5(ts) basically is what converts the ts variable into the MD5 value. b64_md5(ts)的用法基本上是将ts变量转换为MD5值。 However, the ts variable is the ID or name of the Type of Element, not the Element's value itself. 但是, ts变量是Element类型的ID或名称,而不是Element的值本身。

Also, if I wanted to make a cookie that has two values stored in it, a name and a checksum, could I use gh.innerText; 另外,如果我想创建一个存储有两个值的cookie,一个名称和一个校验和,我可以使用gh.innerText; to set the unique name, as I have had issues with using this method so far. 设置唯一名称,因为到目前为止我遇到了使用此方法的问题。

You can use the innerHTML property to get the HTML contents of an element: 您可以使用innerHTML属性来获取元素的HTML内容:

var ts = gh.innerHTML;

Note that h2 elements (and most other elements) don't have a "value". 请注意, h2元素(以及大多数其他元素)没有“值”。 Only elements that behave as form controls have a value property (eg the input element). 只有表现为表单控件的元素才具有value属性(例如input元素)。

If you want to access the type of an element you can just ask for this: 如果要访问元素的类型,可以直接询问:

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)

As mentioned below, accessing the actual node content is a different matter: 如下所述,访问实际节点内容是另一回事:

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

For cross browser access to the text contents use something like this: 对于跨浏览器访问文本内容,请使用以下内容:

var text = gh.innerText || gh.textContent;

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

var text = gh.childNodes.item(0).data;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM