deqoda
deqoda

Reputation: 48

How to select dynamic value with jQuery

I have very funny situation that I can not solve. I have HTML like this:

<div class="pp227">
  <span>Funny text</span>
</div>

Note: this pp can have value from 0 - 500 and this structure need to says as it is. I end up with jQuery code like this:

var selectText = $('.pp[0] > span');

Can anybody have an idea how can I select this value from pp

Upvotes: 0

Views: 492

Answers (4)

ADyson
ADyson

Reputation: 61904

You can select an element based on one part of an attribute - in this case, the start of the class.

So this will work:

[class^='pp'] > span

Also to get the actual text (as opposed to just a jQuery object containing a reference to the selected element(s), you need to use the .text() function.

Demo:

$(function() {
  var selectText = $("[class^='pp'] > span").text();
  console.log(selectText);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pp227">
  <span>Funny text</span>
</div>

Note that this assumes you only ever have one element with a class starting with "pp" in the page at a time. If not, and you want to get the text of all them, then you'll need a loop. You didn't really clarify this in the question.

See https://api.jquery.com/attribute-starts-with-selector/ for more info.

Upvotes: 3

tremendows
tremendows

Reputation: 4382

I assume the array is similar to var pp = [52,356,12,152,...,398];

var selectText = $('.'+pp[0]+' > span');

Javascript allows concatenation between string and int values.

Concatenation is donde with the + operator.

Upvotes: 0

Sarfraaz
Sarfraaz

Reputation: 1269

You can use this wildcard pattern to select elements & then loop through all to get className & value like this,

$("[class^=pp]").each(function(){
  let my_class = $(this).attr('class');
  console.log("Class > ",my_class," Val > ",$(this).find('span').html())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pp227">
  <span>Funny text 1</span>
</div>
<div class="pp226">
  <span>Funny text 2</span>
</div>
<div class="pp225">
  <span>Funny text 3</span>
</div>
<div class="pp224">
  <span>Funny text 4</span>
</div>

Upvotes: 1

Jin-oh Kang
Jin-oh Kang

Reputation: 347

Given there's a variable called index that contains the number:

var myIndex = 117;

You do a string concatenation:

$('.pp' + +myIndex + ' > span')

NOTE: the unary + operator is there to enforce integral value and prevent jQuery injection attacks.

Upvotes: 0

Related Questions