Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Accessing the DOM

One of the most important aspects of JavaScript, and especially jQuery, is the capability to access and manipulate the DOM. Accessing the DOM is how you make the web page dynamic by changing styles, size, position, and values of elements.

In the following sections, you learn about accessing the DOM through traditional methods via JavaScript and the much improved methods using jQuery selectors. These sections are a brief introduction. You will get plenty of practice as the hours roll on.

Using Traditional JavaScript to Access the DOM

Traditionally, JavaScript uses the global document object to access elements in the web page. The simplest method of accessing an element is to directly refer to it by id. For example, if you have a paragraph with the id="question" you can access it via the following JavaScript getElementById() function:

var q = document.getElementById("question");
...
<p id="question">Which method do you prefer?</p>

Another helpful JavaScript function that you can use to access the DOM elements is getElementsByTagName(). This returns a JavaScript array of DOM elements that match the tag name. For example, to get a list of all the <p> elements, use the following function call:

var paragraphs = document.getElementsByTagName("p");

Using jQuery Selectors to Access HTML Elements

Accessing HTML elements is one of jQuery’s biggest strengths. jQuery uses selectors that are very similar to CSS selectors to access one or more elements in the DOM, hence, the name jQuery. jQuery returns back either a single element or an array of jQuerified objects. jQuerified means that additional jQuery functionality has been added to the DOM object, allowing for much easier manipulation.

The syntax for using jQuery selectors is $(selector).action(), where selector is replaced by a valid selector and action is replaced by a jQuerified action attached to the DOM element(s).

For example, the following command finds all paragraph elements in the HTML document and sets the CSS font-weight property to bold:

$("p").css('font-weight', 'bold');
  • + Share This
  • 🔖 Save To Your Account