Sumanth Jois
Sumanth Jois

Reputation: 3234

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>

How can I solve this?

Upvotes: 1

Views: 328

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

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>

Upvotes: 1

brk
brk

Reputation: 50291

In jquery way.

      $(document).ready(function(){
           var spans = document.getElementsByTagName("span");
          for(i=0;i<spans.length;i++){
             alert($(spans[i]).text()); // Changed here
          }
 });

Jsfiddle using jQuery

Using javascript

$(document).ready(function(){

         var spans = document.getElementsByTagName("span");
          for(i=0;i<spans.length;i++){
             alert(spans[i].textContent); // Using textContent
          }
 });

jsfiddle with javascript

EDIT after comments If you are looking for only " Hello How a re You" you need to only retrieve the text form first NodeList of span.

In jquery way

$(document).ready(function(){
 var sp = $('span');
         alert($(sp[0]).text())
 });

Jsfiddle

Upvotes: 0

JF-Mechs
JF-Mechs

Reputation: 1081

You can do it like this

alert($("span")[0].innerHTML.replace(/<(?:.|\n)*>/gm, ''));
<span> Hello How <span>a</span> re You</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 0

Related Questions