2013-02-04 112 views
3

我正在开发一个chrome扩展,它从页面读取html注释并在一个操作弹出窗口中呈现它们。<html><html>标记

但是,我不知道如何(如果有可能)获取<html>标签之前和之后的一些评论。例如:

<!-- test test test --> 
<DOCTYPE html> 
<html> 
... 
</html> 

在jQuery中,$("html").before()$("html").after()都返回相同$("html")

是否有可能使用jQuery或纯Javascript获取这些类型的注释?

编辑:有评论的页面看起来是这样的:

<!-- Comment I'd like to fetch --> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us" > 
<head> 
<title>Featured Designers for WOMEN</title> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> 
<meta http-equiv="Content-Script-Type" content="text/javascript" /> 
<meta http-equiv="Content-Style-Type" content="text/css" /> 
+0

我认为HTML注释不会附加到DOM树上。 –

+1

'jQuery.before()'和'jQuery.after()'*插入*内容:) – jensgram

+0

确实如此,@jensgram!我的坏=) – fegemo

回答

4

有了这个文件:

<!-- comment 1 --> 
<!DOCTYPE html> 
<!-- comment 2 --> 
<html> 
<body> 
hello world 
</body> 
</html> 

你得到这样的第一个注释:

document.firstChild.nodeValue 

第二点意见是发现这样的:

document.childNodes[2].nodeValue 

要下获得所有评论document

var nodes = document.childNodes; 
for (var i = 0, len = nodes.length; i !== len; ++i) { 
    if (nodes[i].nodeType === 8) { 
     console.log('Found comment' + nodes[i].nodeValue); 
    } 
} 
+0

的实际代码更新了问题嘿@Jack,为了得到第二个评论,它可能有效。但是document.firstChild.nodeValue返回null(至少在chrome上)。 – fegemo

+0

@fegemo我在Chrome上测试过它;但我的答案的最后部分应该工作。 –

+0

最后一种方法也不起作用:http://jsfiddle.net/zKk3j/1/ – fegemo

0

document.firstChild应该这样做。

+0

'document.firstChild'正在返回DOCTYPE标记 – fegemo

0

$("html").siblings();这将返回所有与我相信html标签相同级别的dom对象元素。我想通过使用JSfiddle进行确认,但是我现在正在使用IE8在他们的网站上收到Javascript错误。如果在您的测试中无法为您工作,我可以稍后再确认。

+0

'$(“html”)。siblings()'返回一个空数组 – fegemo

+0

html是什么样的? – Jarealist

+0

我用页面 – fegemo