Reputation: 101
JSFiddle here: https://jsfiddle.net/eliluong/wvLrgdw2/
Let's say have an image gallery, and each image is contained within a container with a common class
name. And I have one div
encapsulating everything. I set up a rudimentary example in the JSFiddle code.
If a user clicked on one particular element
in one of the images, the resulting action should do something to all of the images (or maybe a subset). The way I wrote the code was to look until you reach the top most div, and then search to reach the div
element with the stuff I want to change. But I want to figure out how to select only a subset. I can change all of them with $('.myB').text('bye');
but cannot change only some of them by matching on text. But I also am unable to find a correct way to compare the strings right now. Do you have any advice you can give me? Thank you.
*Clarification -- a different question would be, can JQuery get all myB
elements w/contents hello2
as an array, and let me iterate through them all?
$('.one .myB').bind('click', function() {
//alert('test');
//var ttext = $(this).parentsUntil('.one').find('.myB').text();
//$(this).parentsUntil('.one').find('.myB').text('bye');
//$('.myB').text('bye');
if ($('.myB').text() == "hello2") {
$('.myB').text('bye');
}
//alert('text->' + ttext);
});
Upvotes: 1
Views: 50
Reputation: 34234
The question is pretty unclear. If I understand this part correctly
I can change all of them with
$('.myB').text('bye');
but cannot change only some of them by matching on text. But I also am unable to find a correct way to compare the strings right now.
then you may want to do the following:
$('.one .myB').bind('click', function() {
$(".myB").each(function() {
var $this = $(this);
if ($this.text().trim() === 'hello2')
{
$this.css('background-color', 'red'); // just for example
}
});
});
This code will change background of all myB
elements with text contents "hello2" when you click any myB
. Here is the demo.
Upvotes: 0
Reputation: 167212
There could be whitespaces and empty lines inside the <div>
tag. May be try with trim()
:
if ($('.myB').text().trim() == "hello2") {
$('.myB').text('bye');
}
Upvotes: 2