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[edit | edit source]

Retrieving DOM elements[edit | edit source]

Consider the following HTML:

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

By ID[edit | edit source]

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

By Tag Name[edit | edit source]

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

// Number of elements found: containers.length

Modifying Attributes[edit | edit source]

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");