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:
- Once the content has been published and the anchor tag given a url address, I want to check that address and see if there's a specific word in it. If that word is found, then change the anchor text to something of my choice.
- Do the same again but this time checking for a different word in the url string.
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:
- Both anchor tags' text only change to the string of text that I've written in the first else if statement inside the
.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!