CSS, JavaScript and XHTML Explained

Estelle Weyl’s Blog of quirks, random thoughts and funky finds discovered in day-to-day coding

 

XHTML Elements, their parent, children, attributes and default browser presentation November 21, 2008

Filed under: Browsers, DTD, HTML, Web Development — Estelle Weyl @ 12:12 am

XHTML Elements, their meaning, semantics and attributes
<ELEMENT> Element Name Block, Inline, etc. Element’s Parents Element’s Children 3 Browser Presentation

Attributes1

Comments
Elements occuring outside the body element
<!DOCTYPE> Document Type Declaration Not Displayed first line none -   Required. Should be first in the document
<html> html   root element <head> and <body> - xmlns Required
<head> document head Not Displayed <html> <base>, <link>, <meta>, <style>, <script>, <title> other than the title, all the other child elements are not visible to user profile, id, dir, lang. NOT class, style, title Required
<base /> url base for links Not Displayed <head> Empty3 - href, no standard attributes1  
<link /> link Not Displayed <head> Empty3 - href, charset, hreflang, type, rel, rev, media  
<meta /> meta Not Displayed <head> Empty3 - content, name or http-equiv, scheme  
<style> style Not Displayed <head> text - type, media  
<script> script Not Displayed <head> (allowed in <body> too. text or src attribute, not both - type, charset, src, defer do NOT self close with slash. Use end tag
<title> document title   <head> text only seen in the chrome of browser id, dir, lang. NOT class, style, title Required
Elements Occuring in the <body>
<body> document body block <html> Block3   all non-core attributes are deprecated Required
<a> Anchor inline inline or semantic block Text and inline3 except <a> underlined and colored href, hreflang, rel, charset, type, name, rel, rev, shape (rect), coords cannot contain other <a> children

<abbr>

Abbreviation inline inline or semantic block only text / inline3 dotted underline with cursor, tooltip title  
<acronym> acronym inline inline or semantic block only text / inline3 dotted underline with cursor, tooltip title  
<address> address blocktext <blockquote>, <div>, <body>, <form> inline3 elements, <p> italic, block -  
<area /> image map area Not Displayed <map> Empty3 makes hot areas on image alt, shape, coords, href, nohref ‘rect’ is default shape if omitted
<bdo> bi-directional override inline inline or semantic block only text / inline3 reversed text dir, lang  
<blockquote> long quote blocktext   block3 margin: 1em 40px; cite  

<br />

break return or forced line break inline   none line-break does not take internationalizaion attributes use as linebreak in poetry or addresses, not to separate paragraphs.
<button> push button inline   any inline3, except form elements and <a> push button disabled, name, type 2, value, accesskey, tabindex Cannot contain <input>, <select>, <textarea>, <label>, <button>, <form>, <fieldset>, <iframe> or <isindex> as children.
<caption> caption   <table> text and inline3 centered above table - must be first child of the table
<cite> citation inline phrase element text and inline 3 italicized text - -
<code> code inline phrase element text and inline 3 monospace font - -
<col /> column Not Displayed <table> Empty3 - char, charoff, span align & valign allowed, but use CSS instead
<colgroup> column group Not Displayed <table> zero or more <col>   span, char, charoff. align & valign allowed, but use CSS instead while empty, close with an ending </colgroup> tag.
<dd> definition description block <dl> Flow3 indented with a left margin - -
<del> delete inline or block inline or block Flow3 strikethrough cite, datetime don’t put block content in a <del> that is inline

<dfn>

definition inline phrase element only text italic - -
<div> generic block element block   Flow3 - - -
<dl> definition list lists (block)   one or more <dd> and <dt> only - - -
<dt> definition term block <dl> text and inline3 only - - cannot have block elements as children!
<em> emphasized text inline phrase element text and inline3 only italics - -
<fieldset> field set block <form> <legend>, Flow 3 box around child elements with legend, if any - -
<form> form Block block element block elements and block form elements - action, method, enctype, accept, accept-charset cannot nest a <form> within a <form>
<h1-6> headers heading (block) body or block inline and text varying font sizes and bold - -
<hr /> horizontal rule blocktext (block) body or block Empty horizontal line - -
<iframe> internal frame         longdesc,
name,
src,
frameborder,
marginwidth,
marginheight,
scrolling,
align,
height,
width
 
<img /> image inline inline or semantic block Empty The image identified in the src src, alt, longdesc, usemap, ismap height and width are optional attributes best omitted.
<input /> input inline inside a semantic block located in <form> Empty depends on type type, name, value, check, disabled, readonly, size, maxlength, src, alt, usemap, accept type defaults to text if not declared, but you should declare it
<ins> Insert inline or surrounding blocks   Flow underlined cite, datetime don’t put block content in a <del> that is inline
<kbd> keyboard inline phrase element text (and inline) monospace font - should really just be text
<label> label inline semantic block within a <form> text and inline - for, accesskey cannot contain child <label> elements
<legend> caption for fieldset   <fieldset> inline and text top left section of the fieldset box -  
<li> list item block <ul> or <ol> Flow bulleted new line -  
<map> image map Not Displayed   one or more <area> OR block - ID, name  
<object> object     <param>, if included, should come first. Flow   declare, classid, codebase, date, type, codetype, archive, standby, usemap, name, tabindex allowed in <head> by spec. height and width are optional attributes best omitted.

<ol>

ordered list lists (block) block one or more <li> elements indented <li>s with numeric bullets -  
<optgroup> option group   <select> one or more <option> bold, non-selectable header for a group of indented options. label, disabled  
<option> option   <select>, or within <optgroup> textnode appears within the select drop down as new row selected, disabled, label, value if value is omitted, submitted value is the text node value
<p> paragraph block block inline and text new line of text - -
<param /> parameter invisible <object> none not visible, though may cause visual effects id, name, value, valuetype, type can place params as name/value pairs in the object element
<pre> preformatted text blocktext (block)   inline, except <img>, <object>, <sub> & <sup> monospace font and nowrap whitespace - Cannot contain <img>, <object>, <sub>, or <sup> elements
<q> inline quotation inline inline or semantic block inline and text quotes at start and end of content cite (URL) quote style depends on language. Poor browser support of quotes
<samp> sample computer code inline phrase element inline monospace font - -
<select> option selector inline inline or semantic block within <form> one or more <option> required, optional <optgroup> drop down list name, size, multiple, disabled, tabindex  
<span> span (generic non-semantic container) inline inline or semantic block text or inline - -  
<strong> strong emphasized text inline phrase element text or inline bolder text - don’t use in <h1-6> as those are already emphasized
<sub> subscript inline inline or semantic block text or inline smaller, subscripted text - do not include in <pre>
<sup> superscript inline inline or semantic block text or inline smaller, superscript text - cannot be a child of <pre>
<table> data table block block or body <caption>?, (<col>*|<colgroup>*), <thead>?, <tfoot>?, (<tbody>+|<tr>+)) 4 data table summary (width, border, frame, rules, cellspacing, cellpadding)

width, border, cellspacing, cellpadding are allowed, but better to use CSS.

 

<tbody> table body block <table> one or more <tr> appears between thead and tfoot char, charoff in code flow, comes AFTER <tfoot>
<td> table data cell block <tr> Flow vertical align middle, text-align: left abbr, axis, headers, scope, rowspan, colspan,
width, align & valign allowed, but use CSS instead
 
<textarea> text area block <form> or block within form textnode or no text multi-line text field displaying textnode if there is one rows, cols, name, disabled, readonly  
<tfoot> table footer block <table> only one or more <tr> appears at bottom of table char, charoff, width, align & valign allowed, but use CSS instead comes before <tbody>
<th> table header cell block <tr> only Flow bold and center abbr, axis, headers, scope, rowspan, colspan, char, charoff. width, align & valign allowed, but use CSS instead  
<thead> table head block <table> only one or more <tr> only at top of table char, charoff. width, align & valign allowed, but use CSS instead follows opening <table> or <caption> if there is one.
<tr> table row block <table>, <thead>, <tfoot> or <tbody> one or more <th> or <td> new line char, charoff. width, align & valign allowed, but use CSS instead if any of the parent elements are present, there must be at least one <tr>
<ul> unordered list lists (block) block one or more <li> elements indented, bulleted on <li>s - -
<var> variable inline phrase element text (and inline) italic - No reason to include inline elements. Should be just text as child
Elements you should not be using, that are still valid
<tt> teletype inline inline or semantic block text (and inline) monospace - Purely presentational. Should be deprecated, but aren’t yet.
<i> italic italic
<b> bold bold
<big> big font bigger font
<small> small font smaller font
<frame /> frame block <frameset> Empty page within a page

name, src, longdesc, security. frameborder,
marginwidth,
marginheight,
noresize,
scrolling also allowed.

only allowed in frameset DTD
<frameset> frameset block <body> <frame>, <frameset>, <noframes> divides the browser window cols, rows. only allowed in frameset DTD
<noframes> no frames block <frameset> Flow - - can be found outside of frameset (for no iframe support)
<noscript> no script block Flow Flow - - Your site should work without scripts, so should not be necessary

Note:

  1. Attributes: All elements accept the standard and internationalization attributes of id, class, title, style, dir, and lang unless otherwise noted. The attributes column lists elements specific attributes and exceptions to the core attributes. Required attributes have been emphasized.
  2. Even though the type attribute is not required by the specifications, always define type because IE is stupid.
  3. Inline: <a>, <br>, <span>, <bdo>, <map>, <object>, <img>, <tt>, <em>, <strong>, <dfn>, <code>, <q>, <samp>, <kbd>, <var>, <cite>, <abbr>, <acronym>, <sub>, <sup>, <input>, <select>, <textarea>, <label> and<button>
    Block:
    <p>, <h1>, <h2>, <h3>, <h4>, <h5>, <h6>, <ul>, <ol>, <dl>, <pre>, <hr>, <blockquote>, <address>, <fieldset>, <table>
    Flow: text < form > and all the inline and block elements
    Empty: self closing element, include a slash before the end of the opening tag to self close. Contains no children
  4. Table elements: 0 or 1 optional <caption> element, 0 or more optional <col> elements OR 0 or more optional <colgroup> elements, 0 or 1 optional <thead> element, 0 or 1 optional <tfoot> element, and REQUIRED either one or more <tbody> elements OR one or more <tr> elements.
 
 

jQuery Tutorial: DOM Manipulation and sorting November 15, 2008

Filed under: JavaScript, Web Development — Estelle Weyl @ 5:26 pm

JQuery is a lightweight JavaScript library that helps you quickly develop events, animations, and AJAX interactions.

In this tutorial we go over the following:

Note that the test javascript files associated with each section go with the same XHTML file.

Setting up your environment for this tutorial:

  • Download the JQuery library Generally you will want the minified version, but for today, download the uncompressed version so you can read some of the code if you so choose.

  • Save it locally in a directory (let’s call it "js" for this tutorial)

  • Create a new HTML page (Sample file)

  • Link to the JQuery file - <script type="text/javascript" src="js/jquery-1.2.6.js"></script>
    You may need to change the 1.2.6 part to whatever the current release number is.

  • Create a new javascript file, and call it "myCode.js"

  • Link to your javascript file - <script type="text/javascript" src="js/myCode.js"></script>

  • Add some HTML to your page (this is what we’re going to manipulate).

  • You can also add some CSS.

ready method in anonymous function

The first step is to create an anonymous function withing your myCode.js file to encompass all of your javascript. If you take a look at your JQuery file, you’ll note that the entire file is in an anonymous function:

(function(){
 // code here

})();

All of your the code that you create should be included in it’s own anonymous function. This ensures that the jQuery variables are local: your variable declarations will not break the jQuery library, and the jQuery library will not overwrite your variables, methods and properties.

For our own javascript, we are going to encapsulate all our code in an anonymous function. However, since we are accessing elements of the DOM, we need to ensure that the DOM is loaded. We can’t use the parenthesis at the end as in the code above, which executes the anonymous function immediately, since our DOM isn’t loaded yet. We should only execute our anonymous function once we have the DOM. Without jQuery, and without much Javascript skill, the usual route is to include a document.onLoad event. Instead of using onLoad, which makes us wait until all the images are loaded, we’re going to use jQuery’s ready function — $(document).ready() — which executes when the DOM is ready.

The $(document).ready() function has advantages over other load time event handlers. Everything inside it will load as soon as the DOM is loaded, without having to wait for the page contents to be completely loaded. Ready is fired as soon as the DOM is registered by the browser, which allows for hiding and showing effects and other effects as soon as the user sees the page elements. Unlike the onLoad method, which is limited to only one function, the jQuery ready method allows for multiple functions to be loaded within it.

$(document).ready(function() {
 // code here
 });

Add the code above to your myCode.js file.jQuery

Targeting elements in the DOM with CSS and XPath

jQuery enables selecting elements with the same syntax that you would use to target that element with CSS. For example, we can target the first <h2> in our html file these two ways among others: (test js)

  • $("h2:first")
  • $("#mainContent > h2")

Take a look at the official jQuery Selectors page to get a better understanding of how you can use CSS syntax to target elements.

DOM Manipulation

The following are explanations and examples of the DOM manipulation methods provided by the jQuery core. The jQuery domentation for the DOM manipulation methods can be found at http://docs.jquery.com/Manipulation

jQuery’s version of innerHTML and textNodes

jQuery replaces innerHTML with the html() method to both return and set innerHTML with (and without) HTML elements. To return or set text, similar to retrieving and setting textNodes, use jQuery’s text() method. The main difference between the two involves the returning and rendering of HTML elements. (test js)

  • html()
    returns the HTML content of an element. This is directly equivalent to the innerHTML property commonly used by JavaScripters.
    var myHTMLContent = $("#mainContent").html(); // "<h2>My jQuery te…. (to) …functionality</p>
  • html(myString)
    Sets the innerHTML for an element to myString.
    $("h2:first").html(’This is new <em>header</em> content’); // changes the h2, and adds some emphasis
  • text()
    returns the text content, or text nodes, of an element without any markup as one string
    var myTextContent = $("#mainContent").text(); // returns same as html(), but without tags;
  • text(myString)
    Resets the text node value for an element to myString.
    $("h2:first").text(’Ugly <em>header</em>); // escapes ‘>’ and ‘<’ instead of rendering italics

Child & Sibling nodes

append() and prepend() methods: similar to appendChild, except jQuery accepts a string, a DOM element, or a jQuery object as valid arguments. jQuery converts the argument into a text node or element depending on what is passed. (test js)

  1. $("#leftNav ul").append("<li>after the last &lt;li&gt;</li>"); // adds <li> at the end of <ul>
  2. $("#leftNav ul").prepend("<li>before the first &lt;li&gt;</li>"); // adds <li> at the start of <ul>
  3. $("#leftNav ul").append($("#mainContent h2")); // moves headers from the mainContent to the leftNav

  4. $("#leftNav ul").append($("#mainContent h2").html()); //copies text of the first h2, adds it to leftNav

There are two similar methods — appendTo() and prependTo() — which are basically inververted verstions of append() and prepend(). A.append(B) is about equal to B.appendTo(A)

Note: As shown in example 3, if you try to append an element that already exists in the DOM, that element will first be removed from DOM before being reinserted, or appended, in the new location.

before() and after() methods: similar to insertBefore() method (and the non-existant, but found in many javascript libraries, includeing this one, insertAfter()). The after() method inserts a node after a selected one. The before() method inserts a node before a selected one, like the javascript standard method of insertBefore().

  1. $("#leftNav ul").before("<h2>Left Navigation</h2>"); // adds header before the <ul>
  2. $("#leftNav ul").after("<h4>New Header</h4>"); // adds header after the <ul>
  3. $("#leftNav h4").before($("#mainContent h2").html()); //copies text of the first h2, adds it to leftNav before our new <h4>

There are two similar methods — insertBefore() and insertAfter() — which are basically inververted versions of before() and after(). A.before(B) is about equal to B.insertBefore(A)

Parent nodes

wrap(), wrapAll() and wrapInner() methods: wrap selected element or elements in another element. The argument can be an XHTML or DOM element as a string. If the element has child nodes, the element being wrapped will be put in the deepest child node of the first element. (test js)


  1. $("#leftNav ul").wrap("<div class=\"red\"></div>"); // the <ul> gets wrapped in a <div>
  2. $("#mainContent h2").wrap("<blockquote class=\"blue\"></blockquote>"); // the 2 <h2>’s get wrapped in a two separate <blockquote>s
  3. $("#mainContent h2").wrapAll("<blockquote class=\"blue\"></blockquote>"); // the 2 <h2>’s get wrapped in a single <blockquote>, moving the second <h2> up to be the nextSibling to the first <h2>
  4. $("#mainContent h2").wrap(’<div class="shell"><div class="blue"></div><ul class="red"><li></li></ul></div>’); // puts the H2s in two "blue" divs, the LIs will be empty.
  5. $("#mainContent h2").wrapAll(’<div class="shell"><div class="blue"></div><ul class="red"><li></li></ul></div>’); // puts the H2s in ONE "blue" div, the LI will be empty.
  6. $("#mainContent p").wrapInner("<a href=\"#\"></a>"); // puts an <a> between the <p> and the <p>’s first child.
  7. $("#mainContent").wrapInner("<blockquote class=\"blue\"></blockquote>"); // wraps all the children of #mainContent into one parent <blockquote>

remove() and empty()

remove(), empty() and replace() methods: similar to the native javascript removeChild() method, use remove() to remove element(s) from the DOM. Use the empty() method to keep the element, but remove the element’s children.
Note that remove() can take a parameter, but empty() does not. (test js)

  1. $("#leftNav li:first").remove(); // removes the first LI
  2. $("#leftNav li").remove(); // removes all the LIs from the #leftNav
  3. $("#leftNav li").remove(":contains('Second')"); //remove the LI containing the term.
    Note that the string is case-sensitive
  4. $("#mainContent h2:first").empty(); //removes the text in the first H2, but the h2 is not removed from the DOM
  5. $("#mainContent h2:contains('second')").empty(); //removes the text node child of the H2 containing the letters "second"

replaceWith(), replaceAll() and ncloe()

replaceWith() and clone() methods: Cloning creates copies of the DOM elements copied, including the new elements in the DOM, but does not append them to the page. To append the clone to the page, use one of the methods above.

  1. $("#leftNav li:first").replaceWith("<li>new first <em>LI</em></li>"); //text changed, LI is emphasized

  2. $("#leftNav li:first").text().replaceWith("new first <em>LI</em>");// grabs text, and replaces it. No <li> needed
  3. var navCopy = $("#leftNav").clone(); //copies it
    $("#mainContent").append(navCopy); //apends it

    The problem with cloning is that IDs are copied too, and ID’s need to be unique!

Effects with JQuery

The above was an overview of all the DOM manipulation functions. If you’re doing a simple site, those are likely all the javascript helpers you need. But, if that was all you could do with JavaScript, then you really wouldn’t need javascript libraries. The power of the libraries is in everything else they do for you. With jQuery you can create drag and drop, autocomplete, sorting, etc., the is unobtrusive and works cross browser in less than 10 lines of javscript. Proof? Here are two examples:

Sorting a table with javascript:

  1. Create a table in plain old XHTML, and populate that table with data. Give your data table the class of sort with: (sampleFile)

    <table class="sort">
  2. Download the jquery libary and the jquery.tablesorter.js file.

  3. Attach the two jQuery files and your own JavaScript file to your XHTML file by including the following in the header of your XHTML file:

    <script type="text/javascript" src="jquery-1.2.6.js"></script>
    <script type="text/javascript" src="jquery.tablesorter.js"></script>
    <script type="text/javascript" src="myTableCode.js"></script>
  4. In your JavaScript file (called myTableCode.js above) include the simple script:

    $(document).ready(function() {
        $("table.sort").tablesorter();
     });
  5. Literally, the previous step is all there is to sorting tables bu column content in However, that just sorts it based on the content of the HTML. So, if you have an <em> or <p> in one table cell and not in another, it may not sort the way you want. To sort based on a portion of your code inside a cell, use the textExtraction utility provided by jQuery:
    $(document).ready(function() {
    
     $("table.sort").tablesorter({
            // define a custom text extraction function
           textExtraction: function(node) {
                // if there is a link, return the content of the link
    		if(node.getElementsByTagName('a')[0]){
    				return node.getElementsByTagName(’a')[0].innerHTML;
        			}
            return node.innerHTML;
            }
        });
     });

See my example

Making a list sortable

Similar to the sortable table, you can make a make a list that is sortable by dragging list items around. (example)

  1. Create a list, give it the class of "sortable".

    <ul class="sortable">
      <li>This is my first list item</li>
      <li>second list item</li>
      <li>Brief 3</li>
      <li>Long 4</li>
    </ul>
  2. Go to the jQuery Download Builder and select “sortable”. You’ll note that the other required library elements are automatically selected.

  3. Attach the three javascript files downloaded from the builder, and your own javascript file, to your page with the list.

    $(document).ready(function() {
         $("ul.sortable").sortable();
       });

 

Userful Links