How to get class names of all children at multiple levels in jquery?

I want to get class names of children at several levels. I am trying to follow, but it only gives the class names of the back 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 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>
+3
source share
1 answer

You can get a quick array of names a little easier using .map(), for example:

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

Here you can check it out .

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

+2
source

Source: https://habr.com/ru/post/1778080/


All Articles