jQuery text() call preserves newlines in Firefox but not in IE

后端 未结 3 837
梦毁少年i
梦毁少年i 2020-12-01 19:02

I\'m doing:

alert($(\"#div\").text());

on something like this:

<div> Some text <
3条回答
  •  独厮守ぢ
    2020-12-01 19:24

    See here for a workaround:

    The hack is to first clone the element you want the contents of, using cloneNode().

    Next you create a

     element with
      createElement(), and then append your
      cloned node to it.

    Now you can get the innerText of that create

     element, and just delete
      the temporary objects. You now have
      whitespace preserved text :)

    var cloned = targetElement.cloneNode(true);
    var pre = document.createElement("pre");
    pre.appendChild(cloned);
    var textContent = pre.textContent ?
      pre.textContent : pre.innerText;
    delete pre;
    delete cloned;
    

    The reason I clone the element is because the appendChild() would pull it out of the DOM and it's pain the re-insert back at the correct position in the DOM.

    Hopefully this helps a few people out there :)

提交回复
热议问题