Frage

I have a contenteditable div. I am trying to hunt for the word "design" and wrap it in a span element.

HTML:

<div id="text"></div>

JavaScript:

$("#text").prop("contenteditable", true);
var string = $("#text")[0].innerHTML;
$("#text").innerHTML = string.replace("design", "<span>design</span>");

This doesn't work. My first guess would be that its because the script runs once, so by the time I type "design" it doesn't catch it. So, I tried putting it in a setInterval, but that didn't work either. JSFiddle

Any help would be much appreciated.

War es hilfreich?

Lösung

$("#text").prop("contenteditable", true).keypress(function(e){
    $(this).html(function(i,html){return html.replace(/<span>design</span>/g,"design").replace(/design/g, "<span>design</span>")});
});

I didn't test, but hopefully it'll work.

Andere Tipps

You can do it like this

$('#text').prop("contenteditable", true).on('keyup change',function(){
    var $el = $(this);
    $el.find('span').contents().unwrap(); // remove existing spans around "design"
    $el.html(function(i,v){ 
       return v.replace(/\bdesign\b/gi, "<span>design</span>") // wrap design with spans
    });
    setEndOfContenteditable(this); // reset the cursor to the end
});

FIDDLE

the setEndOfContenteditable function was taken from this SO Answer - it sets the cursor back to the end of the text https://stackoverflow.com/a/3866442/1385672

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top