Dive Into Greasemonkey

Teaching an old web new tricks

4.17. Matching case-insensitive attribute values

Many attribute values in HTML are case-insensitive. Many can also contain leading and trailing spaces. If you want to find all variations, you need to do a little legwork in your XPath queries.

Example: Find all forms whose method is "POST" or "post"

var postforms = document.evaluate(
    "//form[translate(@method, 'POST ', 'post')='post']",

This XPath query finds forms that submit with a POST method. First, we need to translate the method attribute to lowercase, using the translate function to convert uppercase letters to lowercase. (XPath 2.0 has a lowercase function, but I didn't have any success using it.) Second, we need to strip leading and trailing spaces. We can incorporate this into our call to the translate function by including an extra space in the first argument. Since there is no corresponding letter in the second argument, all spaces are stripped. Finally, we can compare the resulting attribute value to 'post'.

Real examples

← Post-processing a page after it renders
Getting the current domain name →