Javascript select only inner html of outer element excluding inner element

I am trying to fetch inner html of an Element which has inner element like this

  <span> Hello How <span>a</span> re You</span>

I want fetch only Hello how re You but i am getting like this :

   Hello How <span>a</span> re You

This is my javascript code:

  <script>

      $(document).ready(function(){

         var spans = document.getElementsByTagName("span");
          for(i=0;i<spans.length;i++){


              alert(spans[i].innerHTML);
          }


      });


  </script>

Can anyone tell me how i can solve this?? ThankYou

Answers 1

  • You can either clone the element then remove the child elements and get the contents or filter out the inner content

     $(document).ready(function() {
    
       var $spans = $("span");
       //first way
       $spans.each(function() {
         var text = $(this).clone().find('*').remove().end().text();
         snippet.log('1: ' + text)
       });
    
       //second way
       $spans.each(function() {
         var text = $(this).contents().filter(function() {
           return this.nodeType == Node.TEXT_NODE;
         }).text();
         snippet.log('2: ' + text)
       })
    
    
    
     });
    <!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
    <script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <span> Hello How <span>a</span> re You</span>


Related Articles