How to add an ID to every body tag with JQuery.
This is a quick one, more of a snippet to myself than a legitimate blog post but figured I’d put this here on the off chance this might help some other folks.
Let’s say you are dealing with a CMS or some other legacy / 3rd party system that generates the page HTML of your site in a way that is beyond your control. You might need to get a distinct handle on certain elements of a specific page so you can style them with CSS or perform some JQuery magic.
This little snippet will add an id of the page’s name (swapping / with –) to the body tag of every page. This is injected into the DOM on page load so you won’t see it in regular ‘view source’, but will be able to see it with FireBug or the firefox web developers toolbar ‘view generated source’ option.
As the inline comments say, www.blah.com/this/that/whatever.html, will become body id="this-that-whatever" or, if you are the webroot of your site, body id="home-page". Just add this in your $(document).ready(function() block …
// Duncan hack, get the entire path, turn /s to -s
// strip extension and add that as an id to the body
// so we can target specific pages in the styles if we need to
// www.blah.com/this/that/whatever.html -> body id="this-that-whatever"
// or body id="home-page" if at root /
var pathname = window.location.pathname;
var pathSlashesReplaced = pathname.replace(/\//g, "-");
var pathSlashesReplacedNoFirstDash = pathSlashesReplaced.replace("-","");
var newID = pathSlashesReplacedNoFirstDash.replace(/(\.[\s\S]+)/ig, "");
$("body").attr("id",newID);
if ( $("body").attr("id") == "")
{
$("body").attr("id","home-page");
}
If you instead wanted to add the new identifier as a class, simply use a line like:
$("body").addClass(pathSlashesReplacedNoFirstDash);
instead of
$(“body”).attr(“id”,pathSlashesReplacedNoFirstDash);
Now you can target every page with your CSS / JQuery and make everyone happy! Hooray! This uses javascript regular expressions so may not be as super optimized as it could be using substrings, etc, but it gets the job done.
This is an old post from old blog but google keeps sending people here so I figured I’d backfill it in.
(Examples in C# but easy to do in VB.NET)
If you are slinging ASP.NET for a living or just dealing with lots of string inputs in general, you’ve undoubtedly thought about how you are going to test to make sure your strings have value to them. Lets say you have some querystring parameter that is required for your page to do anything meaningful. So what are you looking to test?
You want to make sure:
1) The string coming in is not null.
2) The trimmed value of the string (providing it is indeed not null) is more than just blank.
Looking to the standard API, you may be tempted to use the built-in String.Empty.
What’s wrong with this seemingly-perfect native method? A small but important item, when it checks for an empty string, there is no trimming involved. In the real world we really never want an input with leading or trailing spaces, and certainly don’t want to accept just a space. Sadly, we can’t pre-trim our string before calling this method as if we do have a null in our hands we will throw and exception trying to trim nothingness.
Ok, next step lets write a couple simple lines of code to test the string ourselves.
Following the FxCop recommendations and good computing sensibilities you’ll find it is cheapest to do the following logic as opposed to say, checking for == “” which is ungood. (C#)
if (stringToTest != null &&
stringToTest.Trim().Length > 0)
{
// its ok!
}
I had this snippet all over the place in my code but was always annoyed that once passing our conditions, including the trim, I had to trim the string anyway inside of the block before I did anything useful with it. What I really wanted was two things at once, to make sure my criteria was met, and if so, to have the “fixed” string in my hand ready to go. Enter the ref. Here is a example of an ASP code-behind calling a helper method StringHasValue that makes life a little easier. In practice, I tuck the StringHasValue method away in a StringUtilities.cs class.
protected void Page_Load(object sender, EventArgs e){
string myString = Request["someParam"];
if (StringHasValue(ref myString))
{
// do things that depend on a myString having a value
// and myString being nicely trimmed.
// such as ….
Literal1.Text = “:” + myString + “:”; // show we are trimmed
}
else
{
Literal1.Text = “Sorry, have no value to speak of”;
}
}
private static bool StringHasValue(ref string stringToTest)
{
bool isOK = false;
if (stringToTest != null &&
stringToTest.Trim().Length > 0)
{
isOK = true;
stringToTest = stringToTest.Trim();
}
return isOK;
}
Now once I’m in my block, having tested if the string has a value, I’m ready to rock with my string and get down to the business at hand. No trimming, no worries. Having StringHasValue as a nice one-liner also lets me simply evaluate a number of params at once with some && action, with all of my strings ready to go.
string myString = Request["someParam"];
string myStringTwo = Request["someParamTwo"];
string myStringThree = Request["someParamThree"];
string myStringFour = Request["someParamFour"];
if (StringHasValue(ref myString) &&
StringHasValue(ref myStringTwo) &&
StringHasValue(ref myStringThree) &&
StringHasValue(ref myStringFour)
)
{
// do stuff
}
Ok, passing values by ref and then acting upon them can be slightly tricky in complex methods as you run the risk of not being able to follow future code, scratching your head wondering how the heck some value gets assigned. I feel in this case though the simplicity of the operation, and a well-named method can make this a pretty reasonable option.