Reputation: 1
hello everyone javascript don't add the class to html
$(".ocmessage").each(function(){
var text = $(this).find('p').html();
if(strpos(text,"<b>"+name+"</b>")!==false) $(this).addClass("quoteme");
});
this code should detect if in <p>...</p>
there are name of some member and if there is javascript should add class quoteme
how can i fix it?
Upvotes: 0
Views: 83
Reputation: 3279
Your elements with class ocmessage
may contain more than one paragraph. So inside the first each
-loop we have to do a second loop through all <p>
like so:
$(".ocmessage").each(function(){
var $T = $(this);
$T.find('p').each(function() {
var text = $(this).html();
// find username and prevent multiple class adding
if(text.indexOf("<b>"+name+"</b>") > -1) {
$T.addClass("quoteme"); return false; // stop loop when class is added
}
});
});
Working FIDDLE here. Credits to Amit Joki.
Upvotes: 0
Reputation: 27247
This is a very poor way to accomplish the task. Here's the more standard jquery way to do it.
$(".ocmessage").has('p b:contains('+name+')').addClass("quoteme");
Upvotes: -1
Reputation: 708
Assuming ocmessage is a div or another contain class.
Take a look at : http://jsfiddle.net/40vv7dbk/
$(".ocmessage").each(function () {
var $this = $(this);
var text = $this.find('p').html();
var name = "Ben"
// Will be -1 if not found.
if (text.indexOf(name) > -1) {
$this.addClass("quoteme");
}
});
What it is doing, is when the document is ready, going through all the Divs with the class ocmessage, looking for a
tag, and then checking if a name is in there. If it does, I add the class quoteme.
Upvotes: 0
Reputation: 59252
I think you mean this. BTW, name
isn't defined.
var name = ''; // change the value
if(text.indexOf("<b>"+name+"</b>") > -1) {
$(this).addClass("quoteme");
}
Upvotes: 2