开发者

How to retrieve class names of all child elements at multiple level in jquery?

开发者 https://www.devze.com 2023-01-29 00:21 出处:网络
I want to retrieve class names of child elements at multiple level. I\'m trying following, but it only gives the class names of rear child elements. What am I doing wrong ?

I want to retrieve class names of child elements at multiple level. I'm trying following, but it only gives the class names of rear child elements. What am I doing wrong ?

    <script type="text/javascript">
    $(document).ready(function(){
    thisP=$("#myParagraph");
  开发者_高级运维  getChildStyles(thisP);
   //function 
function getChildStyles(thisobj) {
var classNames;
var classNames1; 
$(thisobj).children().each(function(){  
    classNames+=$(this).attr('class');
    if($(this).children().length>0) {
            classNames1+=getChildStyles($(this));
        }
        classNames+=classNames1;        
    });
    return classNames;
}   
});
</script>

And the HTML,

   <ul id="myParagraph" class"mainUL">
   <li id="LIOne">ksjdfhsdf</li>
   <li id="LITwo">skdjfkdsf<span class"span1Class"><span class="span2class"></span>  
   </span></li>
   <li id="LIThree" class="thirdLIClass">edroiutret</li>
   </ul>


You can get a quick array of the names a bit simpler using .map(), like this:

$(document).ready(function(){
   var arrayOfClassNames = $("#myParagraph").find("[class]").map(function() {
     return this.className;
   }).get();
});

You can test it out here.

If you want a string you can just do arrayOfClassNames.join('')...or however you want to use it really.

0

精彩评论

暂无评论...
验证码 换一张
取 消