Monday, September 10, 2012

DOM, add text node



Below is the JavaScript to add a text node in DOM when the usersclick the add text node button:
The parent node is p1: <p id="p1">First line of paragraph.<br /></p>
 Using appendChild function to add extra text node
    <script type="text/javascript">
var i=0;
    function addTextNode()
    {
    var newtext = document.createTextNode(" Some text added dynamically. "+(++i));
    var para = document.getElementById("p1");
    para.appendChild(newtext);
    }
 </script>
<div style="border: 1px solid red">
    <p id="p1">First line of paragraph.<br /></p>
    </div>

  <button onclick="addTextNode();">add another textNode.</button>

Demo:
First line of paragraph.


To get p1 node (id is p1) and all its child nodes:
  <script type="text/javascript">
     function getText(n) {
        // Repeated string concatenation can be inefficient, so we collect
        // the value of all text nodes into an array, and then concatenate
        // the elements of that array all at once.
        var strings = [];
        getStrings(n, strings);
        //return strings.join("");

        // This recursive function finds all text nodes and appends
        // their text to an array.
        function getStrings(n, strings) {
            if (n.nodeType == 3 /* Node.TEXT_NODE */)
                strings.push(n.data);
            else if (n.nodeType == 1 /* Node.ELEMENT_NODE */) {
                // Note iteration with firstChild/nextSibling
                for(var m = n.firstChild; m != null; m = m.nextSibling) {
                    getStrings(m, strings);
                }
            }
        }
        alert(strings);
    }
    </script>
 <button onclick="getText(p1);">GetText</button>
Demo:

No comments:

Post a Comment