Reputation: 13
I'm trying to use jQuery to change paragraph text based upon the class of the div in which it resides.
I want each of the class names in the array to replace the p text within their respective divs. Right now I just get the last div's class name for the p text.
<div class="ph player">PHILIPPINES<p class="topic">Test topic</p></div>
<div class="sl player">SOLOMON ISLANDS<p class="topic">Test topic</p></div>
<div class="fi player">FIJI<p class="topic">Test topic</p></div>
<div class="sm player">SAMOA<p class="topic">Test topic</p></div>
<script>
var divArr = ["ph", "sl", "fi", "sm"];
$.each(divArr, function(index, value) {
$(".topic").text(this);
});
</script>
Thanks for looking. Total beginner here.
Upvotes: 1
Views: 884
Reputation: 16020
I THINK what you want is:
$.each(divArr,function(i,val) {
$('.'+val+' p.topic').text(val);
});
That will make the paragraph text of each div equal to the two letter class name
Upvotes: 3
Reputation: 9847
$.each(divArr, function (i,e) {
$("."+this).find("p.topic").text(this);
});
The key is to correctly use the selectors.
"this
" takes the values "ph", "sl"...
So "."+this
will identify classes in JQuery/CSS syntax (.ph, .sl ...)
$("."+this)
therefore selects the correct div
, in which we will fine p
tags with class .topic
and substitute the text (again, this
).
Upvotes: 0
Reputation: 16703
Make sure you are only selecting the div you want to change:
var divArr = ["ph", "sl", "fi", "sm"];
$.each(divArr, function(index, value) {
$("div." + value + " .topic").text(value);
});
Upvotes: 1
Reputation: 50185
You have to find the appropriate .topic
not all .topic
s:
var divArr = ["ph", "sl", "fi", "sm"];
$.each(divArr, function(index, value) {
$('.' + value).find(".topic").text(this);
});
Upvotes: 1