1

How can you change this

<div id='myDiv'><p>This div has <span>other elements</span> in it.</p></div>

into this

<div id='myDiv'>This div has other elements in it.</div>

hopefully using something like this

var ele = document.getElementById('myDiv');
while(ele.firstChild) {
    replaceFunction(ele.firstChild, ele.firstChild.innerHTML);
}
function replaceFunction(element, text) {
    // CODE TO REPLACE ELEMENT WITH TEXT
}

3 Answers 3

2

You can use innerText and textContent if you want to remove all descendant nodes, but leave the text:

// Microsoft
ele.innerText = ele.innerText;
// Others
ele.textContent = ele.textContent;

If you only want to flatten certain ones, you can define:

function foldIntoParent(element) {
  while(ele.firstChild) {
    ele.parentNode.insertBefore(ele.firstChild, ele);
  }
  ele.parentNode.removeChild(ele);
}

should pull all the children out of ele into its parent, and remove ele.

So if ele is the span above, it will do what you want. To find and fold all the element children of #myDiv do this:

function foldAllElementChildren(ele) {
  for (var child = ele.firstChild, next; child; child = next) {
    next = child.nextSibling;
    if (child.nodeType === 1 /* ELEMENT */) {
      foldIntoParent(child);
    }
  }
}

foldAllElementChildren(document.getElementById('myDiv'));
5
  • Thanks for the help. Looks like all I needed was ele.textContent all along.
    – jchavannes
    Feb 10, 2012 at 8:04
  • @jchavannes, It's nice when the simplest solution works. Keep innerText in mind when you test on IE. Feb 10, 2012 at 8:14
  • It's actually a firefox addon so I don't need to worry about IE :P
    – jchavannes
    Feb 10, 2012 at 8:16
  • btw, I tried using your function in jsfiddle: jsfiddle.net/WdE5e and it seemed to remove the <p> but not the <span>
    – jchavannes
    Feb 10, 2012 at 8:16
  • @jchavannes, Yes. You will need to recurse if you want to flatten. Flattening one element at a time gives you more control but requires more work. Feb 10, 2012 at 8:23
0

If you're not opposed to using jQuery, stripping the HTML from an element and leaving only the text is as simple as:

$(element).html($(element).text());
1
  • Can't use jQuery. Thanks though.
    – jchavannes
    Feb 10, 2012 at 7:46
0

You can just take the innerText

console.log(ele.innerText)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.