Sajjad Hossain Sagor
Sajjad Hossain Sagor

Reputation: 518

Fire Event When Javascript InnerText Value Meet If Statements

I am trying to get innerText value and use it in if statement. Something like that : Hypertext codes

<div class="demo">
  <h2 id="txt"><i class="fa fa-male" aria-hidden="true" id="icon"></i>
    Male
</h2>
</div>

Javascript Codes:

    var parentdiv = $( "#txt" ).text();
    if (parentdiv == 'Male'){
      $( "#icon" ).attr( "class", "fa fa-male" );
    }else {
      $( "#icon" ).attr( "class", "fa fa-female" );
    }

it isn't working why? Give me a Solution please.Thanks in advance.

Upvotes: 1

Views: 225

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

The retrieved text content contains whitespace in both end so use String#trim or jQuery.trim() method to replace the trailing and leading space.

var parentdiv = $( "#txt" ).text().trim();
// or
var parentdiv = $.trim($( "#txt" ).text());

Upvotes: 1

Related Questions