3

I have a function, this function receive a string in argument. The content of this variable is HTML code. I'd like know number of HTML element with the class .myClass

function MyTest(myData){
    //get how many element with .myClass are in myData
}

Thanks,

2 Answers 2

9

This is pretty much jQuery 101.

function myTest(myData) {    
  return $( '.myClass', myData ).length;
}

// Usage:
myTest( '<p><span class="myClass">Hello</span> <span class="myClass">world</span></p>' );
// => 2
Sign up to request clarification or add additional context in comments.

3 Comments

It's strange, in "myData", I have this HTML code : <div class="myClass">Testing</div> and I get 0 all the time with your code
For one reason or another jQuery ignores the outermost element. If necessary wrap it in another div, e.g. <div> <div class="myClass">Testing</div> </div>.
Thank you @Jordan. To overcome jQuery ignoring the outermost element, we can also move the identifying class to any inner element.
0

you can use length function

where :

  1. .gradeX =>is your selector of the element
  2. n=> int and holds number of your objects

    $(document).ready(function() { 
    
        var n = $(".gradeX").length;  
        alert(n);  } 
    
    }
    
  3. your jquery linq to reference the methods: http://api.jquery.com/length/ alternative is: http://api.jquery.com/size/

you can have a look here:

http://live.datatables.net/uzelux/edit#javascript,html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.