从jQuery中的标记名称获取第一个元素

时间:2013-04-10 20:09:26

标签: javascript jquery dom

我正在将标准JavaScript转换为jQuery以实现跨浏览器兼容性。我只是想知道如何用jQuery编写它?换句话说,我如何找到第一个元素?

var x = content.getElementsByTagName("title")[0].firstChild.data;

我尝试了以下内容:

var content = $.parseXML(zipEntry1.data);
content = $(content);
var x = content.find("title").first().val();

var content = $.parseXML(zipEntry1.data);
content = $(content);
var x = content.find("title")[0].val();

但这些都没有奏效。什么是正确的方法?

修改

这是一些额外的信息。我正在写一个Epub读者。我正在解析的文件是Epub规范中的content.opf。这是一个摘录:

<metadata>
<dc:rights>Public domain in the USA.</dc:rights>
<dc:identifier id="id" opf:scheme="URI">http://www.gutenberg.org/ebooks/6130</dc:identifier>
<dc:contributor opf:file-as="Buckley, Theodore Alois" opf:role="ann">Theodore Alois Buckley</dc:contributor>
<dc:creator opf:file-as="Homer">Homer</dc:creator>
<dc:contributor opf:file-as="Pope, Alexander" opf:role="trl">Alexander Pope</dc:contributor>
<dc:title>The Iliad</dc:title>
<dc:language xsi:type="dcterms:RFC4646">en</dc:language>
<dc:subject>Classical literature</dc:subject>
<dc:subject>Epic poetry, Greek -- Translations into English</dc:subject>
<dc:subject>Achilles (Greek mythology) -- Poetry</dc:subject>
<dc:subject>Trojan War -- Poetry</dc:subject>
<dc:date opf:event="publication">2004-07-01</dc:date>
<dc:date opf:event="conversion">2012-10-31T19:41:56.338029+00:00</dc:date>
<dc:source>http://www.gutenberg.org/files/6130/6130-h/6130-h.html</dc:source>

  

我可以通过此获取作者和标题,但它仅适用于Chrome:

content.find('creator:first').text();
content.find('title:first').text();

版本适用于Firefox和Chrome:

content.find("package").attr("version");

我还没有公布日期。这就是我试过的:

 content.find('[event="publication"]').val();

3 个答案:

答案 0 :(得分:0)

这样的事可能吗?

var x = content.find('title:first').html()

var x = content.find('title:first').text();

答案 1 :(得分:0)

如果您需要获取第一个标题的文本内容,请使用:

$('title:first', content).text();

然而,Firefox中的jQuery也需要指定名称空间:

var ff = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
$((ff ? 'dc\\:' : '') + 'title:first', content).text();

工作示例:http://jsbin.com/enayex/5/edit

答案 2 :(得分:0)

如果你知道元素类型,那么这很容易。让我们假设我们正在处理div,然后执行此操作:

$('div').first().html("<p>I found you</p>");