Sathya
Sathya

Reputation: 5308

How to parse editable DIV's text with browser compatibility

I make div as editable. while i tried to parse div's text, i was needed to do the below regular expression.

innerDOM = "<div style="cursor: text;">I had downloaded all the material from the Intern,<br>You will find</div><div style="cursor: text;">&nbsp;</div><div style="cursor: text;">dfvdfvdvdfvdfvdvdvdf</div><div style="cursor: text;">&nbsp;</div><div style="cursor: text;">dfvdfvdvdfvdfvdfvdfvd</div>"

innerDOM.replace(/<div style="cursor: text">/g, "<br>").replace(/<\/div>/g, "");

Above regular expression works good in firefox and chrome. But not in IE. What changes should i do?

See this FIDDLE for better understanding...

Upvotes: 3

Views: 9043

Answers (3)

user1792423
user1792423

Reputation:

i found this solution in this site:

$editables = $('[contenteditable=true'];

$editables.filter("p,span").on('keypress',function(e){
 if(e.keyCode==13){ //enter && shift

  e.preventDefault(); //Prevent default browser behavior
  if (window.getSelection) {
      var selection = window.getSelection(),
          range = selection.getRangeAt(0),
          br = document.createElement("br"),
          textNode = document.createTextNode($("<div>&nbsp;</div>").text()); //Passing " " directly will not end up being shown correctly
      range.deleteContents();//required or not?
      range.insertNode(br);
      range.collapse(false);
      range.insertNode(textNode);
      range.selectNodeContents(textNode);

      selection.removeAllRanges();
      selection.addRange(range);
      return false;
  }

   }
});

Upvotes: 3

Sathya
Sathya

Reputation: 5308

//FINAL ANSWER
var domString = "", temp = "";

$("#div-editable div").each(function()
            {
                temp = $(this).html();
                domString += "<br>" + ((temp == "<br>") ? "" : temp);
            });

alert(domString);

see this fiddle for answer.

Upvotes: 3

Laoujin
Laoujin

Reputation: 10249

DOM manipulation is one of the things jQuery was made for. Investing in learning jQuery will take you a long way towards writing DOM traversal and modification.

$("div[style='cursor: text']").unwrap().prepend("<br>");

unwrap deletes the element but keeps the children intact. The jQuery Attribute Equals Selector is used to select all divs with the cursor style attribute. You can run it live here.

You could make this more robust as currently you would not select a div with more or less whitespace or with other trivial differences. For example: <div style="cursor:text;"> is not matched by the above selector. You can work around this shortcoming by introducing a CSS class that sets the cursor. In this case <div style="cursor: text"> becomes <div class='textCursor'> and you can use the class selector: $("div.textCursor")

Upvotes: 4

Related Questions