Reputation: 9066
Here i used an editable div
in which i will write the name of any html element, say <div>
, <body>
this strings. Then selected string will be matched using a regexp pattern and then write again inside a span and changed the letters color into red. But it is not working. I think <>
tag is not letting it happen. How it can be fixed?
<html>
<body>
<div id="mydiv" contenteditable="true" style="width:100%;height:40px;border:1px solid black;overflow:hidden;"><html></div>
<input type="button" value="select" onClick="makeit();">
<span></span>
<script>
function makeit(){
var m=document.getElementById('mydiv');
var text=m.innerHTML;
var p=document.getSelection();
var h=p.toString();
var regex=/<[a-z]+?>/;
var match=h.match(regex);
alert(match+ "matched");
var newelem=document.createElement('span');
newelem.setAttribute("style","color:red;position:relative;top:200px;left:0px]");
newelem.innerHTML=match;
document.body.appendChild(newelem);
}
</script>
</body>
</html>
Upvotes: 1
Views: 1206
Reputation: 19066
This is because the <
and >
are actually <
and >
in the contenteditable div.
Do this:
var regex = /<[a-z]+>/g;
I added the g
assuming you want all matches, if not you can remove it. Also, for some reason you weren't even looking at the text in #mydiv
, you were looking at selected text (which I guess could have happened to have been in #mydiv
). I changed that in the jsfiddle below.
Upvotes: 4