Reputation: 35
I have a simple HTML template that's used multiple times across the document. It's essentially the following div
element wrapping around several p
elements and another div
element with the class button
. For visualization purposes, here's an example:
<div class="content">
<p>First paragraph</p>
<p>Second paragraph</p>
<div><a class="button" href="http://www.apple.com/ipad/">Change me jQuery!</a></div>
</div>
<div class="content">
<p>First paragraph</p>
<p>Second paragraph</p>
<div><a class="button" href="http://www.apple.com/iphone/">Change me jQuery!</a></div>
</div>
Now, the users who will use this template to publish content on the site not always will use the same exact url in that anchor tag, but I do know exactly which ones they can use. So what I'm trying to do with my code is the following:
Here's what I've written:
$('.content').each(function () {
var $this = $(this),
$findP = $this.find('p');
if ($findP.length > 2) {
// Run some code
} else if ( ($findP.length <= 2) && ($('a[href*="ipad"]')) ) {
$this.find('a.button').text('Visit iPad site');
} else if ( ($findP.length <= 2) && ($('a[href*="iphone"]')) ) {
$this.find('a.button').text('Visit iPhone site');
}
});
Issues:
.text()
jQuery method. In my example here, the first anchor tag should take the text "Visit iPad site" while the second one should be "Visit iPhone site". Here's a working fiddle of this example: http://jsfiddle.net/vj4xZ/1/I'm guessing the issue is here that once the first element is found, all anchor tags are assigned what's in the .text() method and the code stops right there without looking for the what's in the second else if statement. If that's the case, or the issue at hand is something else, then how can I get that to working properly? Any help with this will be appreciated. Thank you for your time!
Upvotes: -1
Views: 212
Reputation: 34117
Hiya made a lil different demo here: http://jsfiddle.net/bKJfq/15/
Above demo uses one of this selector: http://api.jquery.com/category/selectors/
http://api.jquery.com/attribute-contains-selector/
once the selector matches it will change the text to the desired text you want.
This can very well be less verbose way; Please let me know if I missed anything.
Hope this helps B-)
code
$('a[href*="ipad"]').text("Visit iPad site");
$('a[href*="iphone"]').text("Visit iPhone site");
Upvotes: 1
Reputation: 255155
http://jsfiddle.net/zerkms/vj4xZ/2/
You need to change your conditions to this:
} else if ( ($findP.length <= 2) && ($this.find('a[href*="ipad"]').length) ) {
$('a[href*="ipad"]')
- means - if there is an anchor with ipad
in href somewhere in the document
What I changed - is limited searching the anchor only by current element with $this.find()
You may also use $('a[href*="ipad"]', $this)
instead, it would do the same work
Upvotes: 2