Search code examples
javascriptjqueryhtmlnestedinline-styles

Nested Tags Spans


I need pass all child inline styles from to the parent only if there aren't text between parent and child.

<span style="text from style"> <!-- this don't recive the childs' style because there are "cccc" -->
        cccc
        <span style="text from style"> <!-- this span recive the style of his child because there aren't plain text between them --> 
          <span style="text from style">
             bbb
          </span>
        </span>
</span>

i got pass the child styles to parent but i can't check if there are text before of after the tag child

this is my script:

currentElement.find('span').each(function(){
                        var $padreSpan = jQuery(this); //get the parent span
                        jQuery(this).find('span').each(function(){ //pass by all span child
                            var styleChildren = jQuery(this).attr('style'); //get them style
                            $padreSpan.attr('style', $padreSpan.attr('style')+ ";" + styleChildren+";"); //set style child to parent
                        });
                        $padreSpan.html(
                                $padreSpan.html().replace(/<span\b[^>]*>/gi,"").replace(/<\/span>/gi,"")
                        ); //clear child spans
                    });

how can i do?


Solution

  • var parent=$('span');    
    var children=$(parent).children();
    

    If you remove all child node what remains is text. Hence:

    var backup=$(children).remove();
    var text=$(parent).text().trim();
    var length=text.length;
    if(length>0){
    //it means there is some text here.
    //all the removed node are there in the backup
    //re insert it anyway you like*
    }