Saturday, October 8, 2016

How to run maven

1 Maven Command (mvn)

The basic syntax for running Maven is:

mvn [options] [<plugin:goal>] [<phase>]

The execution order depends on how goals and build phases are specified on the command line.

2 Running Maven Phases

Example: Compile a project

mvn clean compile

This command removes the previous build output and compiles the project's source code.

3 Running Unit Tests and Integration Tests

Unit tests usually test individual classes or components in isolation. Integration tests verify that multiple components work together, for example an application communicating with a database.

Maven itself does not inherently know whether a test is a unit test or an integration test. The distinction is usually created through plugin configuration and test class naming conventions.

Different Maven plugins can recognize different test class naming patterns. For example, the maven-surefire-plugin is normally used for unit tests, while the maven-failsafe-plugin is normally used for integration tests.

3.1 How Maven Test Plugins Recognize Test Classes

Each test plugin has its own default include patterns. These patterns determine which Java classes are considered test classes and executed by the plugin.

For example, the maven-surefire-plugin, which is normally used for unit tests, recognizes common test class names such as:

Test*.java
*Test.java
*Tests.java
*TestCase.java

Therefore, classes such as the following can be recognized as unit tests:

UserTest.java
TestUser.java
UserTests.java
UserTestCase.java

The maven-failsafe-plugin uses different default patterns for integration tests:

IT*.java
*IT.java
*ITCase.java

Therefore, classes such as the following can be recognized as integration tests:

ITDatabase.java
DatabaseIT.java
DatabaseITCase.java

This naming convention makes it possible to separate unit tests from integration tests while keeping both types of tests in the same Maven test source directory.

Example: Run Unit Tests

mvn test

This command executes the Maven lifecycle up to the test phase. It compiles the application, compiles the test code, and runs the unit tests.

The unit tests are normally executed by the maven-surefire-plugin.

For example:

mvn clean test

This command first removes the previous build output and then compiles and executes the unit tests.

Example: Run Unit Tests and Integration Tests

mvn verify

The verify phase occurs later in the Maven default lifecycle. Therefore, Maven executes all the preceding phases before reaching verify.

If the project is configured with the maven-failsafe-plugin, the integration tests are executed during the integration-test and verify phases.

A common command is:

mvn clean verify

This command performs a clean build, runs the unit tests, packages the application, and executes the integration tests.

The simplified execution flow is:

clean
  |
compile
  |
test
  |---- Unit Tests
  |
package
  |
integration-test
  |---- Integration Tests
  |
verify

3.2 Running Integration Tests with Surefire

Using the maven-failsafe-plugin is the standard approach when you want to separate unit tests from integration tests. However, using two test plugins is not mandatory.

If you prefer to use only the maven-surefire-plugin, you can name your integration test classes using one of Surefire's default test patterns.

For example, both of the following classes match Surefire's default naming conventions:

UserServiceTest.java
DatabaseIntegrationTest.java

Although DatabaseIntegrationTest.java is logically an integration test, its name matches the *Test.java pattern. Therefore, Surefire recognizes it as a test class and executes it together with the unit tests.

For example, consider the following test structure:

src
|
+-- test
    |
    +-- java
        |
        +-- UserServiceTest.java
        +-- RepositoryTest.java
        +-- DatabaseIntegrationTest.java
        +-- JpaIntegrationTest.java

All these classes match the default patterns recognized by the maven-surefire-plugin.

Therefore, the following command executes both the unit tests and the integration tests:

mvn test

Or, for a clean build:

mvn clean test

In this configuration, Maven does not distinguish between unit tests and integration tests. Both types of tests are executed during the test phase by the Surefire plugin.

UserServiceTest.java
RepositoryTest.java
        |
        +----> maven-surefire-plugin
        |
DatabaseIntegrationTest.java
JpaIntegrationTest.java
        |
        +----> maven-surefire-plugin
                    |
                    v
                test phase

This approach can be useful for small projects where running all tests together is sufficient and a separate integration test lifecycle is not required.

However, if integration tests require additional setup or cleanup operations, such as starting and stopping a database, a container, or an external service, using the maven-failsafe-plugin is usually the better approach.

3.3 integration-test vs verify

The integration-test and verify phases are both part of the Maven default lifecycle, but they have different purposes.

The command:

mvn integration-test

runs the Maven lifecycle up to the integration-test phase. Therefore, all preceding phases are executed first.

In a project using the maven-failsafe-plugin, the integration tests are executed during this phase.

For example, the execution flow can be summarized as:

mvn test
    ↓
Unit tests


mvn package
    ↓
Unit tests
    ↓
Package


mvn integration-test
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests


mvn verify
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests
    ↓
Verification of integration-test results


mvn install
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests
    ↓
Verification of integration-test results
    ↓
Install artifact into local repository


mvn deploy
    ↓
Unit tests
    ↓
Package
    ↓
Integration tests
    ↓
Verification of integration-test results
    ↓
Install artifact into local repository
    ↓
Deploy artifact to remote repository

The important difference is that integration-test is the phase where the integration tests are executed, while verify is a later phase where the results of the integration-test execution can be checked.

This is why the Maven Failsafe Plugin is normally configured with both the integration-test and verify goals:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.5.2</version>

    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
</plugin>

For this reason, when you want to perform a complete build including integration tests, mvn verify is generally preferred over mvn integration-test.

The commonly used command is:

mvn clean verify

This performs a clean build, runs the unit tests, packages the application, runs the integration tests, and verifies their results.

In other words, integration-test is mainly the phase where integration testing takes place, while verify is the phase normally used to confirm that the complete build has successfully passed all required checks.

4 Configuring Unit and Integration Tests

Maven uses plugins to execute tests. Each plugin can have its own rules for recognizing test classes.

  • maven-surefire-plugin is normally used for unit tests and recognizes class names such as *Test.java.
  • maven-failsafe-plugin is normally used for integration tests and recognizes class names such as *IT.java.

The naming conventions are important because they allow the two plugins to execute different groups of tests.

The following is a simple pom.xml configuration:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
           http://maven.apache.org/POM/4.0.0
           http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>maven-tests-example</artifactId>
    <version>1.0.0</version>

    <properties>
        <maven.compiler.release>8</maven.compiler.release>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.13.0</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.5.2</version>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>3.5.2</version>

                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>

            </plugin>

        </plugins>
    </build>

</project>

The following diagram summarizes how the two plugins work:

                    Maven Project
                          |
                          |
                 src/test/java
                          |
              +-----------+-----------+
              |                       |
              |                       |
      UserServiceTest.java      DatabaseIT.java
      RepositoryTest.java       JpaIT.java
              |                       |
              |                       |
              v                       v
    maven-surefire-plugin    maven-failsafe-plugin
              |                       |
              v                       v
          test phase         integration-test phase
              |                       |
              +-----------+-----------+
                          |
                          v
                    verify phase

5 Package a Project

Example: Package a project

mvn clean package

This command compiles the code, runs the unit tests, and packages the application into a distributable format such as a JAR or WAR.

Example: Run a Spring Web application

For example, assume you created a Spring Boot web application named my-spring-webapp.

  • To compile the project and produce an artifact, run mvn clean package from the project root.
  • To run the application, execute java -jar target/my-spring-webapp-1.0.0.jar from the project root.

The embedded Tomcat server starts on port 8080. Open your browser and go to http://localhost:8080.

Example: Install to the local repository

mvn clean install

This is one of the most common Maven commands. It builds the project and installs the generated artifact into your local repository, making it available for other local projects.

Maven executes all default lifecycle phases up to install. If Failsafe is configured, integration tests are also executed before the artifact is installed.

Example: Deploy to a shared repository

mvn clean deploy

In a build environment, this command cleans, builds, tests, and deploys artifacts to a remote repository. In multi-module projects, Maven processes each submodule in order and deploys their artifacts.

Introduction to maven

What is Maven ?

Maven is a project management tool, based on the concept of a project object model (POM).
Maven includes a project lifecycle, a dependency management system and execution of plugin goals at defined phases in a lifecycle.

Convention over configuration

Maven uses convention over configuration. Convention over configuration means that the system assume resonable defaults and the user is not required to do the configuration of the system.

Maven's conventions apply to build phases:

  • a maven project is assumed to produce a JAR file.
  • maven defines a default lifecycle and a set of common plugins that know how to build and integrate software.
  • maven core plugins apply conventions for many common processes.

Maven provides default location of directories:

     basedir/
          |__pom.xml
          |
          |__src/
          |   |___main/
          |   |    |___java/       (java source code)
          |   |    |___resources/  (java configuration)
          |   |    |___webapp/     (web content root)
          |   |
          |   |___test                     
          |        |___java/       (test code)
          |        |___resources/  (test configuration)
          |
          |__target/               (generated JAR)
              |___classes/         (compiled code)

The directory src/main is the most important directory, all of its content will become part of the maven artifact

  • the java source code is assumed to be in src/main/java
  • the java configuration are assumed to be in src/main/resources
  • the document root of the web module is src/main/webapp

The directory src/test is the place where tests reside, its content will not become part of the maven artifact:

  • the test sources are assumed to be in src/test/java
  • the test configuration are assumed to be in src/test/resources

The directory target contains the JAR artifact

  • the compiled code is in target/classes

When you use maven, you write your source code and if you follow the conventions, you only have to put the code in the predefined directory, maven will take care of the rest.

Wednesday, September 7, 2016

How To Install Tomcat In OS X

Tomcat Installation

Download the latest binary distribution of tomcat, in my case apache-tomcat-8.0.37.tar.gz, from apache

Extract the file from the tar archive and move the tomcat folder to /opt:

cd Downloads/
tar -xvf apache-tomcat-8.0.36.tar.gz 
mv apache-tomcat-8.0.36 /opt

Set CATALINA_HOME and PATH Environment Variables

$ nano ~/.bash_profile
(~/.bash_profile)

# Set Catalina Home
export CATALINA_HOME=/opt/apache-tomcat-8.0.36
# Export Catalina/bin to path
export PATH=$PATH:$CATALINA_HOME/bin

Common Tomcat Commands

To start tomcat, open a shell Terminal window in any directory and issue the command:

$ startup.sh

Test Tomcat installation by pointing your browser to: http://localhost:8080

To stop tomcat, type on the shell:

$ shutdown.sh

To read the log file:

cd /opt/apache-tomcat-8.0.36/logs
tail -f catalina.out

Manager Web Application

The Manager App is an application that comes with Tomcat and allows you to start, stop, reload and undeploy web applications installed in Tomcat

To allow the access to the Manager App add a manager user to the tomcat users configuration file.

Edit the tomcat-users.xml file:

$ nano /opt/apache-tomcat-8.0.36/conf/tomcat-users.xml

add the following two lines:

<tomcat-users>
...
<role rolename="manager-gui"/>
<user username="manager" password="password" roles="manager-gui"/>
</tomcat-users>

Friday, September 2, 2016

How To Install Maven In OS X

Maven Installation


Download Apache Maven from its website: http://maven.apache.org/bindownload.cgi
Copy the archive file to /opt directory and extract it:
$ cd Downloads
$ cp apache-maven-3.3.9-bin.tar.gz /opt
$ cd /opt
$ tar -xvf apache-maven-3.3.9-bin.tar.gz 

Set M2_HOME and PATH Environment Variables


$ nano ~/.bash_profile
(~/.bash_profile)

# Set Maven Home
export M2_HOME=/opt/apache-maven-3.3.9

# Export Maven bin to path
export PATH=$PATH:$M2_HOME/bin
You can check the PATH by issuing the commands:
$ echo $PATH
/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/apache-ant-1.9.7/bin:/opt/apache-maven-3.3.9/bin
You can check maven installation by issuing the command:
$ mvn -version
Apache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-10T17:41:47+01:00)
Maven home: /opt/apache-maven-3.3.9
Java version: 1.7.0_79, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.11.6", arch: "x86_64", family: "mac"

How to Install Ant in OS X

Ant Installation

Download Apache Ant from its website: http://ant.apache.org/bindownload.cgi

Copy the archive file to /opt directory and extract it:

cd Downloads
cp apache-ant-1.9.7-bin.tar.gz /opt
cd /opt
tar -xvf apache-ant-1.9.7-bin.tar.gz

Friday, August 19, 2016

How To Install JBoss AS 7 in Ubuntu

This guide is aimed at developers wanting to set up their development environment.

First, you should have a JDK-7 installed on your machine. If you have a JDK-8, JBoss AS 7.x will not start.
Then, in your .profile file, set the JAVA_HOME environment variable pointing to java installation.

To download JBoss 7 application server issue the following command on terminal:

wget http://download.jboss.org/jbossas/7.1/jboss-as-7.1.1.Final/jboss-as-7.1.1.Final.tar.gz

Untar the archive:

tar -xvf jboss-as-7.1.1.Final.tar.gz 

Copy the directory to /opt/redhat-jboss-as-7:

sudo cp -r jboss-as-7.1.1.Final /opt/redhat-jboss-as-7

You don't want the jboss process to run as root on your machine, so you need to change the owner and owner group of jboss. Assume you are logged as the user max, to set the owner user and owner group on the jboss directory, issue the following command:

sudo chown -R max:max /opt/redhat-jboss-as-7

To start JBoss type on the shell:

max@ubuntu-host:/opt/redhat-jboss-as-7/bin$ ./standalone.sh

Monday, August 15, 2016

How To Install Tomcat 8 in Ubuntu

Install Oracle's JDK

Install Java, see here

Set the JAVA_HOME, CATALINA_HOME and PATH environment variables

The JAVA_HOME variable is used by Java Servers such as Tomcat and JBoss.

The CATALINA_HOME variable is required by when running Tomcat from command line to locate the files stored in $CATALINA_HOME/conf and $CATALINA_HOME/logs directories.

To set user environment variables edit the ~/.profile:

max@ubuntu-host:~$ nano ~.profile

Append the following lines to the ~.profile file:

export JAVA_HOME=/usr/lib/jvm/java-8-oracle
export CATALINA_HOME=/opt/apache-tomcat-8.0.38
export PATH=$PATH:$JAVA_HOME/bin:$CATALINA_HOME/bin

Thursday, August 11, 2016

How to Install Java In Ubuntu

Which Version of Java to Use?

  • JDK 7 supports:
    • eclipse version 4.4 - 4.5
    • JBoss AS 7 with Java EE 6 features
    • Tomcat 7-8 with WebSockets
  • JDK 8 (LTS) supports:
    • eclipse from eclipse Neon (4.6) to eclipse 2020-06 (4.16)
    • WildFly from 8 to 13 with Java EE 7 features
    • WildFly from 14 to 25 with Jakarta EE 8 features
    • Tomcat 9 with Java EE 8 features
    • Eclipse GlassFish 5.1.0 with Java EE 8 and Jakarta EE 8
    • Eclipse Glassfish 6.0.0 with Jakarta EE 9
  • JDK 11 (LTS) supports:
    • eclipse IDE from Eclipse 4.17 (2020-09) to Eclipse 4.24 (2022-06)
    • Eclipse Glassfish 6.1 with Jakarta EE 9.1
  • JDK 17 (LTS) supports:
    • eclipse IDE from eclipse 4.25 (2022-09) to eclipse 4.28 (2023-06)
    • Eclipse Glassfish 6.2.2 with Jakarta EE 9.1

By march 2019, Java SE 8 will go through the End of Public Updates process, because it is a legacy release.

The java programming language is an open source project. The OpenJDK community works for a free open-source implementation of the Java SE standard and Oracle contribute to the OpenJDK project. Beginning with Java SE 11 (September 2018, LTS), Oracle provide free releases and commercially supported releases for use with Oracle products: OpenJDK (free) and Oracle JDK (commercial) builds from Oracle. The OpenJDK project is the basis for both OpenJDK and Oracle JDK builds: applications will run interchangeably on Oracle JDK-11 and OpenJDK JDK-11.

Monday, July 25, 2016

jQuery and forms

Selecting form controls with jQuery selectors

jQuery selector working with forms are not always the fastest option to select elements: when you use them remember to reduce the number of elements jQuery needs to look through. Orthewise, use common CSS selectors

Example of use of jQuery selectors for forms

/* to start, select all form descendants,
   then, use the filter() method on the initial selection */
var $formDescs = $('form *');

/* :input selects all button, input, select and textarea */
var $inputs = $formDescs.filter(':input');
  
/* :text selects input type="text" and input */  
var $text = $inputs.filter(':text'); 

/* :password selects input type="password" */
var $password = $inputs.filter(':password');   

/* :button selects button and input type='button' */
var $button = $inputs.filter(":button");  

/* :checked selects all checked inputs from group of radio and check inputs */
var checked = $inputs.filter(":checked");

/* :selected selects all selected options from drop boxes */
var selected = $inputs.filter(":selected"); 

Wednesday, July 13, 2016

jQuery Effects

Effects

jQuery effects includes transitions and movements

  • show and hide elements
  • animate elements with fade in and fade out
  • animate elements with slide up and slide down
jQuery method method meaning
Basic Effects $('selector').show() set the display CSS property to element's default value
$('selector').hide() set the display CSS property to none
$('selector').toggle() toggle between showing and hiding elements
Fading Effects $('selector').fadeOut() make element disappear by changing both opacity and display CSS properties
$('selector').fadeIn() make element appear by changing both opacity and display CSS properties
$('selector').fadeTo() change the opacity CSS property
$('selector').fadeToggle() hide or show the element
Sliding Effects $('selector').slideUp() hide the element with sliding movement
$('selector').slideDown() show the element with sliding movement
$('selector').slideToggle() hide or show the element
Custom Effects $('selector').delay() delay the execution of the following method
$('selector').stop() stop the animation
$('selector').animate() create a custom animation

Monday, July 11, 2016

jQuery Traversing and Filtering

DOM Traversing

The jQuery methods for traversing the DOM allow to access other element nodes relative to the initial selection.

jQuery methodmethod meaning
$('selector').find('selector2') all the elements in the current selection matching selector2
$('selector').closest('selector2') the nearest ancestral element matching selector2
$('selector').parent() the direct parent element of current selection
$('selector').parents() all the parents of current selection
$('selector').children() all the children of current selection
$('selector').next() next sibling of current element
$('selector').prev() previous sibling of current element

Monday, July 4, 2016

jQuery and events

Checking When a Page is Ready For Your Code

The ready() method executes its function argument when the page is ready to work

$(document).ready(function(){
  // function body
});
  • Behind the scenes, the ready() method add a listener for DOMContentLoaded events or for load events (in browsers that do not support HTML5 events a load event is fired instead)

There is a shorthand code for the ready() method:

$(function(){
  // function body
});

If you do not wish to use jQuery but still run your code when the page is ready to work, place your script before the body closing tag.

Friday, July 1, 2016

Scripting DOM and CSS with jQuery

Getting and Setting Element Content

The .html() and .text() methods retrive and update the content of elements.

How To Retrieve Element Content

jQuery methodmethod meaning
html = $('selector').html() get the HTML content of the first element in the jQuery selection
text = $('selector').text() get the textual content from every element in the jQuery selection and any descendant

Saturday, May 28, 2016

Introduction to jQuery Library

What is jQuery

jQuery is a javascript library you include in your web pages.
jQuery allows you to select elements using a CSS-style selector and do something with those elements by calling a jQuery method.

Selecting HTML elements with jQuery

$('p');  /* a jQuery object */
  • $() works as short invocation to the jQuery() function
  • $() creates a jQuery object which stores references to the selected elements

Friday, March 11, 2016

CSS Selectors Level 3

1. Selector Syntax

Selector

A selector is one or more sequences of simple selectors separated by combinators, an optional pseudo-element may follow the last sequence of simple selectors

selector = sequenceOfSimpleSelectors [combinator1 sequenceOfSimpleSelectors1 ... ] [::pseudoElement]

A sequence of simple selectors

  • it is a chain of simple selectors that are not separated by a combinator
  • it always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence
  • simple selectors are: type selector, universal selector, attribute selector, class selector, ID selector, pseudo-class.
  • combinators are: whitespace, > "greater-than sign", + "plus sign", ~ "tilde"

The subjects of a selector are the elements of a document tree that are represented by the selector.

1.2 Group of Selectors

A comma-separated list of selectors represents all elements selected by each selector in the list. In CSS, if several selectors share the same declarations, they may be grouped into a comma-separated list.

Example: three CSS rules are condensed into one

h1 { font-family: sans-serif }
h2 { font-family: sans-serif }
h3 { font-family: sans-serif }
is equivalent to:

h1, h2, h3 { font-family: sans-serif }

Thursday, February 18, 2016

Types of JavaScript Events

W3C DOM Events

DOM Level 2 UIEvent: user interface events occur for interactions with browser's window
type event description target
load Fires when HTML and all resources of a web page have finished loading document, window
unload Fires when web page is unloading for a new page requested body, window
error Fires when browser encounter a JS error or resource does not exist (inconsistent support)
resize Fires repeatedly as browser's window is being resized window
scroll Fires repeatedly as user scrolls web page document, element

Usage:

  • The load event is commonly used to trigger scripts that access the content of a page. It can cause the page to look slow, because it is raised only when all images are fully loaded.
  • As resize and scroll events fire repeatedly, do not use them to trigger complicated code.

Thursday, February 11, 2016

JavaScript Events

Types of Events

In a browser events are dispatched to objects to signal that something has happened, such as network activity or user interaction.
  • W3C DOM Events Interfaces
    • UIEvent: user interface events occur for an interaction with browser's window
    • FocusEvent: occur when an element (link or form field) gains or loses focus
    • MouseEvent: occur when user uses mouse, touchscreen, trackpad
    • KeyboardEvent: occur when user uses keyboard
    • [deprecated] MutationEvent: occur for a modification of DOM structure or DOM node
    • MutationObserver: occur for a modification of DOM structure or DOM node
  • W3C HTML5 Events Interfaces
    • FormEvent: occur for an interaction with form element
    • Various Interfaces: occur for an interaction with web page
  • Vendor Specific BOM Events
    • Events that deals with touchscreen and accelerometer

Friday, January 15, 2016

The DOM API


Browsers come with a set of built-in objects that model data used and operations performed by your applications:
  • The Browser Object Model API (BOM) features Window object that models browser's windows and tabs.
  • The Document Object Model API (DOM) features Document object that models web pages displayed in browser's windows.

The DOM API specification serves two purposes:

  • how browser should make a model of HTML documents using objects:
    When a browser loads a web page, it creates a structure, a DOM tree, that is a live representation of the web page. The DOM tree is made of Node objects and each node represents an element that is part of the web page.
  • how JS programs can access this model for changing HTML documents:
    JavaScript program can access the DOM tree for modifying the HTML document. This does not change the HTML code, but only the DOM, the representation of the document.

Friday, January 1, 2016

HTML attributes and DOM Element properties

HTML Global Attributes

An HTML element consists of a tag and a set of attributes, an attribute being a pair name="value".

HTML Global attributes are attribute common to all HTML elements. They are divided in three subtypes: core attributes, event-handler attributes and xml attributes

HTML 4.1 Core Attributes
  • id: a unique identifier for the element
  • class: classifies similar elements, for semantic purposes or for presentation purposes.
  • style: adds presentational properties to the element
  • title: attaches textual explanation to the element
  • lang: defines the language of the element
  • dir: the reading direction
  • accesskey: indicates a keyboard shortcut key
  • tabindex: specifies the tab order index
HTML 5 Core Attributes
  • contenteditable: specifies whether a user can edit the content of the element
  • contextmenu: specifies a <menu> for the element
  • data-*: custom attribute for the element
  • draggable: specifies whether a user can drag the element
  • hidden: hides the element
  • spellcheck: specifies whether the element should be checked for spelling and grammar or not
  • translate: specifies whether content of the element is to be translated or not when page is localized

Example: attributes of <body> element

See the Pen DOM tree: document.body.attributes by Massimiliano De Simone (@maxdesimone) on CodePen.

HTML Attributes as DOM Element Properties

In the DOM an HTMLElement object represents an element of an HTML document. The attributes of an element become properties of the corresponding DOM HTMLElement object.

For example, you may set up google analytics for your web site, in that case you have to include in the home page a script like the one below, where you create a <script> element and then you set the attributes type, async and src using the dot notation.

<script>
var _ga = document.createElement('script'); 
 _ga.type = 'text/javascript'; 
 _ga.async = true;
 _ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
<script>