skip to Main Content

I’m not able to figure out how to count all the characters of an html string using jquery:

For example:

<link rel="stylesheet" type="text/css" href="style.css" id="basic">

I wanna do something like:

var object = $('#basic');
var characters = object.numberOfCharacters;

The answer should be = 67

3

Answers


  1. You can simply do:

    $('#basic')[0].outerHTML.length
    

    There isn’t really a jQuery function available for this purpose, but luckily Vanilla-Javascript is capable of getting the .outerHTML property directly from the (first) selected DOM element of the jQuery object.

    Login or Signup to reply.
  2. You can get the ‘outer’ HTML property to get the tag/element selected and then count the length of that element.

    See sample code below

    $(function() {
      let linkObj = $('#basic');
      console.log(linkObj.prop('outerHTML').length);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <link rel="stylesheet" type="text/css" href="style.css" id="basic">
    Login or Signup to reply.
  3. You can try this in jquery

    
    <!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>
    </head>
    
    <body>
        <div id="myDiv">
            <div>
                <h1>Testing Log</h1>
            </div>
        </div>
    
        <script src="https://code.jquery.com/jquery-3.7.0.min.js" integrity="sha256-2Pmvv0kuTBOenSvLm6bvfBSSHrUJ+3A7x6P5Ebd07/g=" crossorigin="anonymous"></script>
    
        <script>
            var content = $('#myDiv').html();
            console.log(content);
            //remove white spaces
            content = content.replace(/ /g, '').replace(/n/g, '');
            var characterCount = content.length;
            console.log('count:', characterCount);
        </script>
    </body>
    
    </html>
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search