Reputation: 181
So I what I'm trying to accomplish 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.net/vuDzC/2/ to make it more clear.
Thanks
Upvotes: 2
Views: 4214
Reputation: 1680
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>
Upvotes: 1
Reputation: 27585
$(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
});
Upvotes: 0
Reputation: 144729
You 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>');
});
Upvotes: 5