skip to Main Content

myTags.html

<div id="ControlWrapper">
    <p>​</p>
    <p><br></p>
    <p>​​</p>
</div>

myScripts.js

var a  = $("#ControlWrapper").text();
    if (a == ""){do something;}else {do something else;}

<div id="ctl00_PlaceHolderMain_txtContent__ControlWrapper_RichHtmlField" class="ms-rtestate-field" style="display: block;" aria-labelledby="ctl00_PlaceHolderMain_txtContent_label">
    <p>​</p>
    <p><br></p>
    <p>​​</p>
</div>

Hi, i have the above codes in my html and javascrpt files.

I want to get text from an element and save it in a variable then if it is empty it should return false in a conditional statement, but unfortunately it doesn’t work.

I need to comapre the text when there is no text inside an element.

3

Answers


  1. You could try if (!a) {...}

    !a gives true when a is undefined, null or empty.

    If you’re in a browser you can use console.log('[',a,']'); to see which value a has.

    Login or Signup to reply.
  2. $(document).ready(function(){
      var a = $("#ControlWrapper").text();
      console.log(a);
      if (!a) {
        console.log("true value")
      } else {
        console.log("false value")
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="ControlWrapper">
      <p></p>
      <p><br></p>
      <p></p>
    </div>

    This code exactly logs out "false value" as there is no text included inside the HTML node children elements.

    Login or Signup to reply.
  3. In my opinion, we can use trim() (to remove spaces) method to specify a javascript conditional statement like this:

    myScripts.js and myDocument.html

      function getText() {
          var text = $('.element').text();
          if (text && text.trim() !== '') {
              console.log(text);
          } else {
              alert("Empty");
          }
      }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    
        </style>
    
    </head>
    <body>
       
        <div class="element" class="element">
        </div>
    
        <button onClick="getText()">
            Show Text 
        </button>
        
    </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search