Home > Software engineering >  How can i get text content in a nested span?
How can i get text content in a nested span?

Time:03-08

this is html and javascript code I was trying to create to get the value inside last span tag:

var value2=$('#jsVal span .EmbeddedMiniatureVisualization')[0];

console.log(value2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="jsVal">
<span id="36eb3c8a1503436b8b0a79ce1758d05a" style="">
    <span id="89e56665-5959-4e67-8fb8-83ca7cef9965" viewid="89e56665-5959-4e67-8fb8-83ca7cef9965"  sf-busy="false" style="position: relative; margin: 0px; padding: 0px; border: 0px; overflow: hidden;">
        <span style="color: rgb(79, 79, 79); text-align: right;">53338060787</span>
    </span>
</span>
</div>

From developer tools, I see that it returns this:

<span id="89e56665-5959-4e67-8fb8-83ca7cef9965" viewid="89e56665-5959-4e67-8fb8-83ca7cef9965"  sf-busy="false" style="position: relative; margin: 0px; padding: 0px; border: 0px; overflow: hidden;">
    <span style="color: rgb(79, 79, 79); text-align: right;">53338060787</span>
</span>

So from this, How can i get the text inside span? Is there a more straightforward way?

I tried this:

var value=$('div#jsVal span span.EmbeddedMiniatureVisualization span').text().trim();

but I get null value...

CodePudding user response:

Because you are not fullyg going to the element that you want in text format. I suggest to go deep and apply text to each element then only it will work.

See in the image I get two different a=output for each almost same querryenter image description here.

The first output i get is list of nan values

The second Output I get is the list of elements that I want.

See my ipynb file for your reference if you want here is the link : https://github.com/PullarwarOm/devtomanager.com-Web-Scraping/blob/main/devtomanager Final.ipynb Thank you.

CodePudding user response:

You could ask for the last element that doesn't have a child, at any point.. so from the top

$("#jsVal :not(:has(*))").text();

or from anywhere below

$("#jsVal span.EmbeddedMiniatureVisualization :not(:has(*))").text();

Target the highest level at which you can guarantee it is what you want, by ID or Class

  • Related