17

I am simply attempting to get jquery to identify the first letter of a paragraph. How would I do this?

For example, I have a page with a number of paragrahs on a page. I would like only the paragraphs starting with a specified letter to be given the class "current" and all others to be hidden. I pretty much know how to add the class and hide the others but, I cant get jquery to recognize the first letter.

Secondly, is it possible to pull this 'first letter' variable from the url string?

For example, Page 1 - There is a list of letters. The user clicks 'B' and the url is

http://domain.com/page2.html?letter=b

And page2 picks up that variable (b) and applies it to the Jquery, showing only those paragraphs

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Batfan
  • 7,966
  • 6
  • 33
  • 53
  • Will you be using a server-side language like PHP to retrieve `$_GET['letter']`, or do you want to do this with jQuery as well? – BoltClock Jun 14 '10 at 17:45
  • It really doesnt matter to me either way. I'm not opposed at all to working with some PHP as well. – Batfan Jun 14 '10 at 17:56
  • I updated my answer in case you choose to handle it with client-side code. – BoltClock Jun 14 '10 at 18:04

5 Answers5

25

Try:

jQuery('p').each(function(){     
    if(jQuery(this).text().substr(0,1).toUpperCase() == 'B'){
         jQuery(this).addClass('someclass')
    }
   })

You can use PHP to clean the variable and the print it in JS:

<script type="text/javascript">
var letter = '<?php  echo (strlen($_GET['letter']) == 1) ? $_GET['letter'] : ''; ?>'
</script>

Or just grab it with document.location and extract it.

Aaron Butacov
  • 32,415
  • 8
  • 47
  • 61
  • Remove the `if`. The `if` keyword is not present in a ternary operator. – BoltClock Jun 14 '10 at 17:58
  • @BoltClock - Thanks for the pointer. I have removed the If and it is now pulling the letter from the string. However the variable doesnt seem to be populating in the jquery. – Batfan Jun 14 '10 at 18:13
  • 1
    Yah, sorry about that I had a full `if` statement and just grabbed it. @batfan, if `var letter` is defined in the global space (outside a function), it should be accessible to the function by just using `if(jQuery(this).text().substr(0,1).toUpperCase() == letter){`. – Aaron Butacov Jun 14 '10 at 18:17
  • Though, you might be better off just grabbing it with JS. – Aaron Butacov Jun 14 '10 at 18:18
  • @Aaron - Thanks for that. It still wasnt working after I changed that but, then I tried changing the letter in the string from 'b' to 'B' and it worked. Does it have to be in caps? Also, it only displays the first paragraph that matches this letter. How do I get it to show all matches? – Batfan Jun 14 '10 at 18:25
  • It is better to set both the input and the match to uppercase (or lower case) you can change the PHP to include `strtoupper($_GET['letter'])` to force both to be uppercase in case the user changes it from one to the other. As far as I can tell, it works for all `

    ` tags.

    – Aaron Butacov Jun 14 '10 at 18:37
  • @Aaron - Im checking the page using Firebug and it looks like the class "current-series" is being applied to all matching

    tags but, all but the first one are being hidden.

    – Batfan Jun 14 '10 at 18:42
  • 1
    Is the page this is happening on live? One alternative, is to just and an `}else{ jQuery(this).hide();}` to the code above and have it all done at once. It might get rid of whatever is conflicting. – Aaron Butacov Jun 14 '10 at 18:45
  • @Aaron - I had one more question on that script. Is there a way to also hide all but the first item, for each set of matching values? – Batfan Jun 14 '10 at 21:03
  • Hmmm, if this doesn't work, open a new question. `$(this).html(letter + '');` – Aaron Butacov Jun 14 '10 at 21:13
  • @Aaron - Thanks for your continued help. This did not work. It wrapped the span tags around all but the first letter, for each item. New question posted - http://stackoverflow.com/questions/3041066/hide-all-but-first-matching-element – Batfan Jun 14 '10 at 21:26
  • @Aaron - With the variables that are passed from the URL, the letters are working great but, is there a way to have a single variable pull pull all paragraphs starting with a number? For example, domain.com/index.php?letter=0 – Batfan Jun 15 '10 at 16:40
  • `if(parseInt(jQuery(this).text().substr(0,1))) //do something else` – Aaron Butacov Jun 16 '10 at 15:08
12

If you'd like to use JavaScript to grab the letter from the URL query string, run a regular expression on window.location.search:

var letterParam = window.location.search.match(/letter=([a-z])/i), letter;

if (letterParam)
{
    letter = letterParam[1];
}

To match paragraphs starting with that letter, use the charAt() method in JavaScript strings:

if (letter)
{
    $('p').each(function()
    {
        if ($(this).text().charAt(0).toUpperCase() == 'B')
        {
            // Apply the CSS class or change the style...
        }
    });
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
8

To hide the <p> tags whose text does not start with the letter B:

$('p').filter(function() {
  return $(this).text().charAt(0).toUpperCase() != 'B';
}).hide();
John Rasch
  • 62,489
  • 19
  • 106
  • 139
5
$('p').hide().filter(function(){return $(this).text().match(/^b/i);}).show();

or indented

$('p').hide()
      .filter(
              function(){
                         return $(this).text().match(/^b/i);
                        }
             )
      .show();

remove the i in the match if you want it to be case sensitive..

and you can look at http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html on how to get the url parameters..

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
3

I don't know if its relevant here, but I am using this to style the first character.

$(".menu ul li.page_item a").each(function() {
var text = $(this).html();
var first = $('<span>'+text.charAt(0)+'</span>').addClass('caps');
$(this).html(text.substring(1)).prepend(first);
});

cheers!

foxybagga
  • 4,184
  • 2
  • 34
  • 31
  • 1
    Hey, I just got this working using two characters, so substr() instead of charAt(), but this was just what I needed. – lharby Aug 07 '13 at 13:56