【发布时间】:2013-12-19 23:11:26
【问题描述】:
在给定文本节点或 Xpath 的路径的情况下,我需要获取 元素 的句柄。
我使用以下方法返回元素。
result.singleNodeValue; 返回 null 如果存在多个 childNode,我可以将它们合并为一个吗?
function xpathElement(expr) {
var resolver = function (prefix) {
if ("xhtml" == prefix) {
return "http://www.w3.org/1999/xhtml";
}
}
var result = document.evaluate(expr, document, resolver, 9, null)
console.log("function xpathElement: possible multiple nodes:");
console.log(result);
result = result.singleNodeValue;
console.log("function xpathElement: singleNodeValue:");
console.log(result);
return result;
}
作品:
当我传入以下内容时,它返回一个文本节点很好
/xhtml:html[0001]/xhtml:body[0001]/xhtml:div[0002]/xhtml:div[0001]/text()[0001]
不起作用:
当我传入以下内容时,它 返回 null
/xhtml:html[0001]/xhtml:body[0001]/xhtml:div[0002]/text()[0003]
这是我正在使用的 html
<p class="calibre1">
<a id="itr"></a>
</p>
<div class="fmhT">
<b class="calibre3">INTRODUCTION</b>
</div>
<div class="fmtx">
Between 1843 and 1848, Dickens wrote five novellas or long short stories that he
published at Christmastime (<i class="calibre6">A Christmas Carol</i>, The Chimes, The
Cricket on the Hearth, The Battle of Life, and The Haunted Man and the Ghost’s Bargain).
The stories are not merely set at Christmas or the New Year’s holiday but contain themes
the author felt were particularly appropriate to the season. While Christmas celebrations
predate Dickens and there existed before him a tradition of telling ghost-tales at
Christmas and the turn of the year, Dickens breathed a new and unique vigor into these
celebrations and traditions that carry forward to this day. He wrote other ghost stories,
almost all of which are spoofs or farces, but in his “Christmas books” allowed
supernatural elements a power to awaken characters and readers from their social
misanthropy.
</div>
似乎这个元素 <i class="calibre6">A Christmas Carol</i> 将文本节点分成 3 个部分<div class="fmtx"> 的子节点
节点 1
“在 1843 年到 1848 年间,狄更斯写了五部中篇小说或长篇短篇小说,并在圣诞节期间发表(”
节点 2
“圣诞颂歌”
节点 3
》、《钟声》、《炉膛上的蟋蟀》、《生命之战》和《鬼魂与鬼魂的交易》)。这些故事不仅以圣诞节或新年假期为背景,还包含作者的主题感觉特别适合这个季节。虽然圣诞节的庆祝活动早于狄更斯,而且在他之前就存在着在圣诞节和年初讲鬼故事的传统,但狄更斯为这些庆祝活动和传统注入了新的和独特的活力。这一天,他写了其他鬼故事,几乎都是恶搞或闹剧,但在他的“圣诞书籍”中,超自然元素具有将人物和读者从社会厌世中唤醒的力量。
"
我如何将这些文本节点组合为一个?
我试过
$('.fmtx').normalize(); 没有运气,仍然显示 3 个 childNodes。
任何帮助将不胜感激,谢谢!
更新
我添加了一个 jsfiddle,也许这会更有意义,http://jsfiddle.net/95Bc7/
密切关注+++++++++++++++++ ancestor xpath element: null 底部的控制台日志
1)在斜体文本之前进行选择
+++++++++++++++++ ancestor xpath element: [object Text]
2)在斜体文本上进行选择
+++++++++++++++++ ancestor xpath element: [object Text]
3)在斜体文本之后进行选择
+++++++++++++++++ ancestor xpath element: null
【问题讨论】:
-
这是复制粘贴问题吗?您的“有效”和“无效”示例是相同的..
-
$('.fmtx').innerText会得到所有的潜台词。 -
$('.fmtx').text(function(text){return text;});可能会做你想做的事,不过我不确定。你的问题让我有点困惑。 -
啊是的,让我更新不起作用的例子:)
标签: javascript jquery html dom