So I what I'm trying to acplish here, is to change the color of words affected by some regex.
$(document).ready(function(){
container = $("#modal_container section").text();
hashtags = /\#\w+/g;
var container_hash = container.match(hashtags);
$(container_hash).css({'color':'red'});
//We're grabbing the words, but how can I change the color?
alert(container_hash);
});
Here's a fiddle / to make it more clear.
Thanks
So I what I'm trying to acplish here, is to change the color of words affected by some regex.
$(document).ready(function(){
container = $("#modal_container section").text();
hashtags = /\#\w+/g;
var container_hash = container.match(hashtags);
$(container_hash).css({'color':'red'});
//We're grabbing the words, but how can I change the color?
alert(container_hash);
});
Here's a fiddle http://jsfiddle/vuDzC/2/ to make it more clear.
Thanks
Share asked Apr 20, 2013 at 23:04 AaronAaron 1811 gold badge4 silver badges12 bronze badges 1- You can't change the colour of individual words in the sense of arbitrarily selecting some of an element's text. You'd need to wrap each word in, say, span elements, and then change the colour of each span. – nnnnnn Commented Apr 20, 2013 at 23:06
3 Answers
Reset to default 5You can't change color of textNodes/texts, you should wrap the matching text with an element and then style that element.
$("#modal_container section p").html(function(_, html) {
return html.replace(/(\#\w+)/g, '<span class="red">$1</span>');
});
http://jsfiddle/vuDzC/4/
This sort of does that you're looking for (or should be a good enough example):
<script type="text/javascript">
$(document).ready(function(){
var text = $("#modal_container").html();
var myRegExp = new RegExp('\\#\\w+','gi');
var newtext = text.replace(myRegExp,'<span style="color:red;">$&</span>');
$("#empty").html(newtext);
});
</script>
<div id="modal_container">
#works<br />
# Desnt Work<br />
Not Even Close<br />
</div>
<div id="empty" style="margin-top:30px;">
</div>
$(function(){
var container = $("#modal_container section");
var htmlWrappedHashtags = container.html().replace(/\(#\w+)/g, '<span class="red">$1</span>');
container.html(htmlWrappedHashtags);
$(".red").css({'color':'red'}); // or better: include ".red {color: red;}" into your CSS
});