Balancing Tags in HTML and XHTML Excerpts

It is fairly common to want to take an HTML source of variable length and display an excerpt. Although some formats, such as Atom and RSS, anticipate this and create a separate summary element, we don’t always have the luxury of using such a data source.

Creating an excerpt introduces a problem, though: if we create an excerpt based on a number of words or characters, we may end up with unbalanced HTML or even broken tags.

One solution is to discard all tags and display plain text, but this is often unsatisfactory.

Here is my method of balancing tags. It assumes that the input is an excerpt of a valid XHTML snippet. The reason for this requirement has to do with self-closing tags, which I hope will be apparent from the description:
Continue reading Balancing Tags in HTML and XHTML Excerpts

Opening links in a new window without the target attribute

Web developers often use the attribute target="_blank" to force a link to open in a new window. However, if you use an HTML validation service to check your web pages, you know that the target attribute is not valid in strict versions of HTML and XHTML.

There is a simple way to have a link open in a new window using Javascript. You may have seen code like this:
<a href="#" onclick="window.open('http://osric.net')">osric.net web hosting</a>

That method has some serious drawbacks, though:

  • The user now sees # in the browser’s status bar instead of the actual destination URL
  • The link fails if the Javascript fails (or if the browser has Javascript disabled
  • Search engines may not follow the link

I’ve written a summary of the issue and the methods I’ve found so far that best address it. I moved it to a page outside this blog because of the Javascript examples, which were easier to include on a separate page:

How to best use Javascript to open links in a new window