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'));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the help. Looks like all I needed was ele.textContent all along.
@jchavannes, It's nice when the simplest solution works. Keep innerText in mind when you test on IE.
It's actually a firefox addon so I don't need to worry about IE :P
btw, I tried using your function in jsfiddle: jsfiddle.net/WdE5e and it seemed to remove the <p> but not the <span>
@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.
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 Comment

Can't use jQuery. Thanks though.
0

You can just take the innerText

console.log(ele.innerText)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.