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:



         var spans = document.getElementsByTagName("span");




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;
         snippet.log('2: ' + text)
    <!-- Provides the `snippet` object, see -->
    <script src=""></script>
    <script src=""></script>
    <span> Hello How <span>a</span> re You</span>

Related Articles