I imagine this is a jQuery solution, but I'm struggling to get my head round the required syntax.

say I have:

<div id="content-header">
   <h1 class="title">Home</h1>

how would I set about adding a class to div#content-header to match the first letter of the h1?

e.g. I'd like to end up with:

<div id="content-header" class="letter-h">
  <h1 class="title">Home</h1>


<div id="content-header" class="letter-a">
  <h1 class="title">About Us</h1>

2 answers

This was chosen as the best answer

Or something like this:

 $("#content-header ").addClass( 'letter-' + $(this).find(h1).eq(0).text().substring(0,1).toLowerCase() );

By using eq(0) you are sure your getting the first <h1> inside the #content-header.

Answered over 7 years ago by Jens Hedqvist
  • Ah, yes. I meant to put $(foo).children("h1:first") as my selector, which would do the same thing as eq :) Olly Hodgson over 7 years ago
  • Touch! :P Jens Hedqvist over 7 years ago

Something like this ought to do the trick:

var foo, bar;
foo = $("#content-header");
bar = $(foo).children("h1:first").text().substring(0,1).toLowerCase(); // toLowerCase is optional
$(foo).addClass("letter-" + bar);

You may need to trim leading whitespace from the front of $(foo).children("h1").text(), in which case jQuery.trim would help.

Answered over 7 years ago by Olly Hodgson