skip to Main Content

I want to get the span text using jQuery so my html code is like below

Note :- actually this logic was in table data so I given example code only.

<div class="strategiesddata">
<div class="strattabletodivmobright">
<p class="stategybuysellchkbox clearfix">
<span class="BUY active" name="spbuy">B</span>
<span class="SELL " name="spsell">S</span>
</p></div>

<div class="strattabletodivmobright">
<p class="stategybuysellchkbox clearfix">
<span class="BUY " name="spbuy">B</span>
<span class="SELL active" name="spsell">S</span>
</p></div>
</div>

In the above html code I have two active, buy or sell div’s so my query is if it active span then I should take that span text

ex:- From first div B and next div S text I should take

For this I have written jQuery like this

$(".strategiesddata").each(function () {
 t = $(this);
var tst = t.find(".stategybuysellchkbox").closest(".active").html();
});

And

$(".strategiesddata").each(function () {
 t = $(this);
var tst = t.closest(".stategybuysellchkbox").find("span[.active]").html();
});

But I’m getting the value is undefined Suggest me where I did the mistake and how to achieve this?

2

Answers


  1. Your jQuery statement is wrong, try this.

    var tst = $(".stategybuysellchkbox").find(".active").text();
    
    Login or Signup to reply.
  2. To reference the elements in question, you should be able to simply use

    $(".stategybuysellchkbox span.active")
    

    One issue here is that jQuery’s methods like text() and html() will only get you the contents of the first element in the collection.

    To get an array of all the text, use .map()

    const activeText = $(".stategybuysellchkbox span.active")
      .map((_, span) => span.textContent).get();
    
    console.log(activeText);
    .active { color: red; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
    <div class="strattabletodivmobright">
    <p class="stategybuysellchkbox clearfix">
    <span class="BUY active" name="spbuy">B</span>
    <span class="SELL " name="spsell">S</span>
    </p></div>
    
    <div class="strattabletodivmobright">
    <p class="stategybuysellchkbox clearfix">
    <span class="BUY " name="spbuy">B</span>
    <span class="SELL active" name="spsell">S</span>
    </p></div>

    You definitely don’t need jQuery for this either

    const activeText = Array.from(
      document.querySelectorAll(".stategybuysellchkbox span.active"),
      (span) => span.textContent
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search