一个textNode可以有一个childNode是一个elementNode吗? [英] can a textNode have a childNode which is an elementNode?

查看:95
本文介绍了一个textNode可以有一个childNode是一个elementNode吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,以下可能:

textNode.appendChild(elementNode);

elementNode 指的是 nodeType 设置为1

textNode 指的是 nodeType 设置为2

生产不容易。

我问这个问题的原因是我发现一个功能,在引号的末尾添加了一个引用链接:

The reason I ask this is that I find a function that adds a cite link to the end of a quotation:

function displayCitations() {
  var quotes = document.getElementsByTagName("blockquote");
  for (var i=0; i<quotes.length; i++) {
  if (!quotes[i].getAttribute("cite")) continue;
  var url = quotes[i].getAttribute("cite");
  var quoteChildren = quotes[i].getElementsByTagName('*');
  if (quoteChildren.length < 1) continue;
  var elem = quoteChildren[quoteChildren.length - 1];
  var link = document.createElement("a");
  var link_text = document.createTextNode("source");
  link.appendChild(link_text);
  link.setAttribute("href",url);
  var superscript = document.createElement("sup");
  superscript.appendChild(link);
  elem.appendChild(superscript);
  }
}

查看最后一行 elem.appendChild(superscript); 其中 elem 可以是一个 textNode

see the last line "elem.appendChild(superscript);" where elem can be a textNode?

我认为很难证明它的原因是因为很难访问指定的 textNode 。有人有办法实现吗?

I think the reason it's difficult to prove it because it's hard to get access to a specified textNode. Have anyone any way to achieve that?

推荐答案

不,文本节点总是叶。相反,您必须向文本节点的父级添加新节点,使其成为文本节点的兄弟节点。

No, text nodes are always leafs. Instead you must add new nodes to the text node's parent - making them siblings of the text node.

这里是一个例子,我试图添加一个孩子到文本节点。

Here's an example where I attempt to add a child to a text node.

<div id="test">my only child is this text node</div>

<script type="text/javascript">

var div = document.getElementById( 'test' );
var textNode = div.childNodes[0];
var superscript = document.createElement("sup");
superscript.text = 'test';

textNode.appendChild( superscript );

</script>

Firefox发出错误

Firefox gives the error


未捕获的异常:

(NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)中的指定点插入节点不能

uncaught exception: Node cannot be inserted at the specified point in the hierarchy (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)

这篇关于一个textNode可以有一个childNode是一个elementNode吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆