Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can a textNode have a childNode which is an elementNode?

Tags:

javascript

dom

Say,is the following possible:

textNode.appendChild(elementNode);

elementNode refers to those with nodeType set to 1

textNode refers to those with nodeType set to 2

It's not easy to produce.

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);
  }
}

see the last line "elem.appendChild(superscript);" where elem can be a 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?

like image 694
omg Avatar asked Jul 10 '09 18:07

omg


2 Answers

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.

EDIT

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 gives the error

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

like image 93
Peter Bailey Avatar answered Sep 30 '22 01:09

Peter Bailey


I don't think so; I'm fairly certain that something like

<div>this is some <a href="...">text</a> with an element inside it.</div>

ends up being:

<div>
    <textnode/>
    <a>
        <textnode/>
    </a>
    <textnode/>
</div>

I don't believe textNodes can have children.

If I had to guess, I'd think that the result of adding a child node to a text node would be to add the element to the text node's parent instead, but I've not tested that at all.

like image 26
technophile Avatar answered Sep 30 '22 01:09

technophile