Jason
Jason

Reputation: 462

Using jQuery find string A or B and replace based on css class and ID

Using jQuery, how do you check for and replace the occurrence of stringA or stringB when it falls under a specific css class and ID?

stringA = " | "
stringB = "|" 
css     = .login #bav

<div class="login">
    <p id="nav">
        <a href="#">oh ya</a> |
        <a href="#" title="Password Lost and Found"></a>
    </p>
</div>

I have variations of this:

jQuery(document).ready(function($) {
  $(".login #nav").replaceText( /testA|testB/gi, "fooBar" );
  });
});

Upvotes: 0

Views: 228

Answers (2)

Manoj Yadav
Manoj Yadav

Reputation: 6612

You can do like this

jQuery(document).ready(function($) {
    var stringA = " | ";
    var stringB = "|";
    var nav = $("#nav");
    nav.html(nav.html().replace(stringA, "fooBar").replace(stringB, "fooBar"));
});

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

With what I understand of your problem, I'd suggest:

$('#nav').contents().each(function(){
    if (this.nodeType === 3) {
        var str = this.nodeValue;
        this.nodeValue = str.replace(/(\|)|(\s+\|\s+)/g,'foobar');
    }
});

JS Fiddle demo.

References:

Upvotes: 1

Related Questions