Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 553
  • Last Modified:

Can a node of type TEXT_NODE ever have a sibling?



Can a node of type TEXT_NODE ever have a sibling? If so please provide an example.

Thanks!
0
0h4crying0utloud
Asked:
0h4crying0utloud
  • 2
1 Solution
 
dakydCommented:
Yes, they can.  In the example below, the <p> is the parent, there is a text node, and the span is its sibling.  Hope that helps.

<html>
<head>
<script type="text/javascript">
function checkForSib()
{
  var obj = document.getElementById("parent");
  var txtNode = obj.childNodes[0];
  alert("node has type of " + txtNode.nodeType + " and value of '" + txtNode.data + "'");
  var sib = txtNode.nextSibling;
  alert(sib + ": " + sib.innerHTML);
}
</script>
</head>

<body>
<p id="parent">some text <span style="font-weight: bold">sibling of "some text"</span></p>

<form>
  <input type="button" onclick="checkForSib();" value="check for sibling">
</form>
</body>
</html>
0
 
0h4crying0utloudAuthor Commented:


Doh!  what I meant was can a textNode ever have another textNode sibling. But you anwser is correct to this question, I'll post another.
0
 
dakydCommented:
Ah, I misunderstood then.  I did some testing, and in a normal HTML document, browsers are smart enough to combine the two would-be text nodes.  An interesting side note is that in the Mozilla browsers, a new line between two html tags causes a textnode to be inserted.  So this:

  <tr>
    <td>blah ...

   Would mean that the first child of the <tr> would be a text node with just "\n", and the second child would be the <td>.  It has to do with the implementation of the browser, but that construct is fairly common, so you often get "extra" text nodes all over the DOM if you're using that browser.

That aside, it's still technically possible to do what you're asking.  It's a bit contrived, but you can use the DOM to forcibly insert a textnode anywhere you want, including as the sibling of another text node:

<html>
<head>
<script type="text/javascript">
function addTxtNode()
{
  var obj = document.getElementById("parent");
  var txt = document.createTextNode(" world");
  obj.appendChild(txt);

  alert("text node1: '" + obj.childNodes[0].data + "'\n" +
        "text node2: '" + obj.childNodes[1].data + "'");
}
</script>
</head>

<body>
<p id="parent">hello<p>

<form>
  <input type="button" value="make text node siblings" onclick="addTxtNode();">
</form>
</body>
</html>
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now