Tuesday, August 23, 2005

Get tags using CSS selectors (Javascript)

These functions query a web page and gets all elements using CSS selectors. Could be seen as more powerful versions of getElementByTagName. cssQuery is by the author of IE7 (not the new browser being developed by Microsoft, but a hack to improve CSS support in IE 5 or later). It has recently had an update to cssQuery Version 2 to support more selectors. getElementsBySelector is similar to this and is less powerful and is used via document.getElementsBySelector.

An example of where this might be useful is if you wanted to change all links that opened in a new window to open in the current window instead and be made bold:

var tags = cssQuery("a[target='_blank']");
for(i=0;i<tags.length;i++) {
  tags[i].setAttribute("target", "");
  tags[i].style.fontWeight = "bold";
}


Tags: , ,

No comments: