Tag Archives: HTML attributes

jQuery: creating new tags

We’ve seen that we can select existing elements on a web page in many ways using the $(selectorsyntax, where ‘selector’ can take on any of the many forms we’ve seen in earlier posts. The $() syntax can also be used to create new HTML which can then be inserted into your document.

To do this, simply put the desired HTML (enclosed in quotes) directly as the argument. Thus $(‘<input type=text/>’) creates a new text input box.

Merely creating a new object does not, however, insert it into the document. To do that, you need to use a method such as appendTo(). Thus  $(‘<input type=text/>’).appendTo(‘body’) will add the text box to the end of the body, so that it appears at the bottom of the page.

The easiest way of trying this feature out is to load a page (such as the one we’ve been using for examples up to now) that uses jQuery into a browser such as Chrome that has a console, and then typing some commands into the console. The results should be instantly visible on the page.

That’s about all there is to say about the single-argument method of creating HTML. There is, though, another version, in which a second argument can be passed. This second argument allows attributes to be specified.

It’s true that we could just include all the attributes in the raw HTML in the first argument, but it’s sometimes cleaner and easier to read if we can lay out the attributes more explicitly.

For example, we could create a new text input as follows:

$('<input />',
  {
    type: 'text',
    title: 'A test text box',
    click: function () {
      alert($(this).attr('title'));
    },
    css: {
      backgroundColor: 'peachpuff',
      border: '2px dotted red'
    }
  }).appendTo('body');

We’ve moved the ‘type’ attribute to the second argument, and added a ‘title’ (which is displayed as a tooltip when the mouse hovers over the text box). We’ve also added an event handler for a mouse click, which just displays an alert box containing the title. (It’s probably more conventional to add the event handler using a method, but putting it in the attribute list is perfectly valid.)

We’ve also added a couple of style properties in the css attribute. The css attribute is a bit odd in that it gets translated to a ‘style’ attribute in the HTML, and some of the attribute names get changed. For example, the css ‘backgroundColor’ is changed to ‘background-color’ in the style. You can, if you like, specify the ‘style’ attribute explicitly in the jQuery, but you’ll have to use the style names instead of the css names, and put the whole set of styles into a single string. The above example would be written:

$('<input />',
  {
    type: 'text',
    title: 'A test text box',
    click: function () {
      alert($(this).attr('title'));
    },
    style: 
      'background-color: peachpuff; border: 2px dotted red' 
 }).appendTo('body');

jQuery selections: id, class and attributes

In the last post, we saw how to select page elements by searching for tag names. Sometimes, we’d like to select elements based on other criteria. There are several ways of labelling or marking tags.

For the purposes of an example, we’ll modify the body of the page given in the previous post, so it now becomes:

<body>
  <h2>jQuery Selectors</h2>
  <table>
    <tr>
      <th colspan="2">Comic Summary</th>
    </tr>
    <tr class="headerRow">
      <th id="comicHeader" class="header cell">Comic</th>
      <th id="numberHeader" class="header cell">Number</th>
    </tr>
    <tr>
      <td class="cell">Thor</td>
      <td class="cell">34</td>
    </tr>
    <tr>
      <td class="cell">Superman</td>
      <td class="cell">158</td>
    </tr>
    <tr>
      <td colspan="2">
        Which is best?<br />
        <label> <input type="radio" name="dcMarvel" /> DC</label>
        <label> <input type="radio" name="dcMarvel" /> Marvel</label>
      </td>
    </tr>
    <tr>
      <td colspan="2">
      What are your favourites?
        <ul>
          <li><label><input type="checkbox" />Batman</label></li>
          <li><label><input type="checkbox" />Superboy</label></li>
          <li><label><input type="checkbox" />Fantastic Four</label></li>
          <li><input type="checkbox" />Iron Man</li>
          <li><input type="checkbox" />Incredible Hulk</li>
          <li><input type="checkbox" />Green Lantern</li>
        </ul>
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="text" id="jqtest" /></td>
    </tr>
  </table>
</body>

First, a tag may be given an id attribute. The HTML standard specifies that no two visible page elements may have the same id. The key word here is ‘visible’; you can define several page elements with the same id, so long as only one of them (or none of them) is visible at any given time. In the example above, we’d added an id to each of the th tags in the table.

Secondly, most page elements can be assigned a class to which they belong. The name ‘class’ is a bit misleading if you’re familiar with object oriented programming, since an HTML class doesn’t have many of the properties of a true OOP class. In HTML, a class is really little more than a label which can be used to identify groups of tags on a page. In the above HTML, we’ve assigned all the td elements to have the class ‘cell’. Unlike the id, the class of a tag need not be unique; in fact, it usually won’t be, since the idea is normally to identify a set of tags that have a common property.

A tag can belong to more than one class. In the above code, the th tags are members of both the ‘header’ and ‘cell’ classes. To define multiple classes, we list the class names separated by whitespace. Both the id and class can be any valid string.

Finally, many tags have various attributes. Although these attributes are usually used to specify some properties of the tag, they can also be used as identification. Actually, both the id and the class are attributes, but there are many others for some tags. In the above example, the first th tag has a ‘colspan’ attribute, and the radio and checkbox input tags have ‘type’ attributes (the radio buttons also have a ‘name’ attribute).

One of the most common uses of these ways of labelling tags is in specifying CSS rules, but we can also use them in jQuery selectors to pick out groups of elements on which we can act. Using the above page as an example (you can use the same head as the last section if you want to try this a live browser), we can see a few examples.

Searching using the id

To use an id, prefix the the id name with a #. For example, the expression $(‘#comicHeader’) will find the th tag with that id. Note that although ids must be unique amongst visible elements, it is possible that some currently hidden tags may have the same id, and this expression will find all tags that have that id, so you may need to filter the results to be sure of getting the one you want.

If you want to restrict the search to tags of a certain name, simply prefix the id name with the tag name. Thus $(‘th#comicHeader’) will find all th tags with an id of comicHeader (which happens to give the same result as the earlier example in this case).

It’s important to note that there is no whitespace between the th and the #. If you did put a blank between them, you would then be searching for descendents of a th node that had that id, which in this case would return an empty list. If you tried $(‘tr #comicHeader’), though, you’d then get the comicHeader node again, since it’s in a node which is a descendent of a tr node.

You can search for several ids by separating them with commas. Thus $(‘#comicHeader, #numberHeader’) finds both th nodes with ids.

Searching using the class

Using the class as a search term is pretty much the same as using the id except you prefix the class name with a period (.) instead of #. Thus $(‘.cell’) finds all tags with a class of ‘cell’.

Somewhat counter-intuitively, although you can define a tag that belongs to two classes by listing the class names separated by whitespace, if you try finding all tags that belong to both of two classes in the same way, you are doomed to fail. For example, the query $(‘.header .cell’) returns an empty list. What this query is really asking for is a list of elements with a class of ‘cell’ that are descendents of a tag with class ‘header’. Thus if we tried $(‘.headerRow .cell’) we’d then get the two th tags with a class of ‘cell’.

If you do want a list of tags that belong to both of two different classes, you have to leave out the whitespace. Thus $(‘header.cell’) will give you the two th tags again.

You can combine ids and classes in the same search. Thus $(‘#comicHeader.header.cell’) looks for tags that have an id of comicHeader and classes of both ‘header’ and ‘cell’.

Searching using attributes

Finally, you can use any attribute as a search term. The syntax for this encloses the attribute and its value in square brackets. For example, to find all checkboxes, we can use $([type=checkbox]). We’ve left the quotes off ‘checkbox’, but in fact it doesn’t seem to matter whether you use them or not; thus $([type=”checkbox”]) also works.

You can also search for tags that merely have a given attribute, regardless of what value that attribute has. For example, we can get a list of all tags that have ids by writing $([id]). The notation above for searching on id or class isn’t quite just a shorthand for using the id and class attributes though. The class has its own logic that allows things like multiple class definitions and searches, as we saw above. If we tried something like $([class=header]) we’d get an empty result. The attribute search attempts to match the exact string to the attribute, and there is no tag with just ‘header’ as its class, so the search fails.