lolfika
lolfika

Reputation: 1

Javascript don't add the class

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

Answers (4)

Martin Ernst
Martin Ernst

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

000
000

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

Ben Temple-Heald
Ben Temple-Heald

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

Amit Joki
Amit Joki

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

Related Questions