Javascript

From Leo's Notes
Last edited on 12 January 2016, at 18:45.

This page will contain some common vanilla javascript information. Not Javascript frameworks such as jQuery or AngularJS.

Operations

Retrieving DOM elements

Consider the following HTML:

<div id="link-container">
  <a id="link" href="#">Click Me</a>
</div>

By ID

var container = document.getElementById('link-container');

By Tag Name

var containers = document.getElementsByTagName('div');

// Number of elements found: containers.length

Modifying Attributes

With an element selected, attributes can be modified using getAttribute(name) and setAttribute(name, value).

var link = document.getElementById('link');

// url set to href attribute, currently '#'
var url = link.getAttribute("href");
link.setAttribute("href", "http://leo.leung.xyz");