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
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.
If the span with the text you want is always the 2nd child of element with class
subexample2
you can use: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.
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.