skip to Main Content

I am trying to retrieve a span text -cnn.com from the below structure using jquery.

var txt = $(".example1 >.myNewTest").closest('.subexample2').find('span').text();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="example1" id="test1">
  <div id="wkTest" class="myNewTest">
    <h2 class="subexample2">
      <span class="moreTest></span>
      <span>cnn.com</span>---->I need this.
      <span>/</span>
      <span>News</span>
    </h2>
  </div>
</div>

3

Answers


  1. Since you have multiple span elements, a good way to differentiate them is by adding an id to the span you want to retrieve. Once you have done this, it is easy to retrieve the text using .innerHTML.

    var cnn = $('#cnn')[0].innerHTML
    console.log(cnn)
    <div class="example1" id="test1">
      <div id="wkTest" class="myNewTest">
        <h2 class="subexample2">
          <span class="moreTest"></span>
          <span id="cnn">cnn.com</span>
          <span>/</span>
          <span>News</span>
        </h2>
      </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
  2. If the span with the text you want is always the 2nd child of element with class subexample2 you can use:

    const txt = $('.example1 > .myNewTest > .subexample2 > span:eq(1)').text()
    
    const txt = $('.example1 > .myNewTest > .subexample2 > span:eq(1)').text()
    
    $('#result').val(txt)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="example1" id="test1">
      <div id="wkTest" class="myNewTest">
        <h2 class="subexample2">
          <span class="moreTest"></span>
          <span>cnn.com</span>
          <span>/</span>
          <span>News</span>
        </h2>
      </div>
    </div>
    
    <input type="text" id="result">
    Login or Signup to reply.
  3. If you don’t have the option to add a class name or ID to the element, you can try this one below. + selector targets immediate sibling element.

    var txt = $(".example1 >.myNewTest > .subexample2 > .moreTest + span").text();
    

    Well if you can add a class then it would be much simpler, check the below code. website is the class name used to target the element.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="example1" id="test1">
      <div id="wkTest" class="myNewTest">
        <h2 class="subexample2">
          <span class="moreTest"></span>
          <span class="website">cnn.com</span>
          <span>/</span>
          <span>News</span>
        </h2>
      </div>
    </div>
    
    var txt = $(".example1 .website").text();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search