简体   繁体   中英

How to remove all div tags, but not content, which it have? (Working with contenteditable=“true”, HTML5)

How to remove all div tags, but not content, which it have? (Working with conteneditable="true", HTML5)

I have a not real textarea - just <div> with contenteditable="true" . When I'm pressing 'submit' button, code is reading innerHTML of this element. It's not good.

So, I want to use it as textarea, I need to:

  1. Remove <div> tags without content (when I'm starting new line, browser closing previous <div> (if exist) and starting new <div> .
  2. Remove all other tags, different from <br /> (but if <br> tags more than 2 on a row, delete it).

How to realize it? On server side and on user side (because it sends by xhr).

get your parent <div> , clone the node, and traverse the cloned Tree: remove the <div> Nodes, which have no content, and the other disallowed tags.

When you finished Traversing, you the can submit what is left of your Dom-Element.

I have used content editable divs in the past, the best way to use them is indirectly; rather than having them throw the content at php, have a hidden textarea somewhere, with the submit button in that (the submit not hidden obviously) and then the content editable div elsewhere. You can then use jQuery to grab the content of your div and then use some funky regex to parse it for your <br /> and <div> and </div> tags.

<div contenteditable="true" style="width:200px; height:100px;" id="InputDiv">
...
</div>

<form action="something.php">
    <textarea id="InputArea" style="visibility:hidden;">
    <input onclick="getData()"type="submit" value="submit" >
</form>

With the corresponding jQuery:

function getData(){
    var rawDiv = $("#InputArea").text();
    var parsedStr = /*some funky regex*/;
    $("#InputArea").text(parsedStr);
}

I seem to have misplaced my previous work with jquery and contenteditable divs, but something along this line should work.

An alternative:

Rather than using content editable divs, why not use markdown? There would be less need to sort out this kind of problem.

这可以解决问题:

document.getElementById(/*your_div_to_be_removed*/).removeNode(false);

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