简体   繁体   中英

In dojo, how would I erase an inner text node without erasing other nodes inside the element also?

I have

<div>
    blah
    <div>blah2</div>
</div>

I want to erase 'blah' without erasing blah2

How would I do it?

Using the latest dojo, 1.10.

I am not sure whether it can be done only using dojo.
The below code uses a mix of dojo and plain javascript objects to achieve your desired result.

your problem statement.(note: I have added an id attribute "mydiv" to the parent div).

<div id="mydiv">
    blah
    <div>blah2</div>
</div>

Deleting all the text node 'blah'.

// require the query and domReady modules
require(["dojo","dojo/query", "dojo/domReady!" ], function(dojo,query) {
   // retrieve an array of nodes with the ID "list"
   var list = query("#mydiv")[0];
   console.log("list:",list);
   var childNodes = list.childNodes;
   var len = childNodes.length;
   var i;
   for ( i = 0; i < len; i++){
       // Destroy All textnodes.
       if ( childNodes[i].nodeType === 3 ) {
          //console.log ("Text node found");
          dojo.destroy(childNodes[i]);
       };
   } 

})

Courtesy of Tim Down: How to remove text (without removing inner elements) from a parent element using jquery This is supposed to work since IE5 according to him.

require(["dojo/query", "dojo/domReady!"], function(query) {
var parent = query("#parentid")[0];    
var nextchild;
var child = parent.firstChild;

while (child) {
nextChild = child.nextSibling;
if (child.nodeType == 3) {
parent.removeChild(child);
}
child = nextChild;
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM