Projekt

Obecné

Profil

Stáhnout (2.36 KB) Statistiky
| Větev: | Tag: | Revize:
1
/**
2
 * Class containing Document Object Model utility functions.
3
 * @constructor
4
 */
5
function DOM() {
6
	var htmlTags = JSON.parse(document.getElementById('htmlTags').textContent);
7
	var svgTags = JSON.parse(document.getElementById('svgTags').textContent);
8

    
9
	/**
10
	 * Creates a new HTML DOM element from HTML string. Since only the first HTML element in the set is returned, the input 
11
	 * string should contain a wrapping element that would hold all inner elements.
12
	 * 
13
	 * @param {string} html HTML string.
14
	 * @returns {Element} HTML element.
15
	 */
16
	this.htmlStringToElement = function(html) {
17
		var template = document.createElement('template');
18
		template.innerHTML = html;
19

    
20
		return template.content.firstChild;
21
	};
22

    
23
	/**
24
	 * Creates a new HTML DOM element. If the tagName passed as a parameter is not a valid HTML tag, exception is thrown.
25
	 *
26
	 * @param {string} tagName Type of the newly created element (div, span, ...).
27
	 * @param {object} attributes Attributes of the element.
28
	 * @returns {Element} HTML DOM element.
29
	 * @throws {InvalidArgumentException} Thrown when tagName is not a valid HTML tag.
30
	 */
31
	this.createHtmlElement = function(tagName, attributes) {
32
		if (htmlTags.indexOf(tagName) === -1) {
33
			throw new InvalidArgumentException(tagName, 'is not a valid HTML element');
34
		}
35

    
36
		var element = document.createElement(tagName);
37
		for (let key in attributes) {
38
			element.setAttribute(key, attributes[key]);
39
		}
40

    
41
		return element;
42
	};
43
	
44
	/**
45
	 * Creates a new SVG DOM element. If the tagName passed as a parameter is not a valid SVG tag, exception is thrown.
46
	 *
47
	 * @param {string} tagName Type of the element (circle, rect, ...).
48
	 * @param {object} attributes Attributes of the element.
49
	 * @returns {Element} SVG DOM element.
50
	 * @throws {InvalidArgumentException} Thrown when tagName is not a valid SVG tag.
51
	 */
52
	this.createSvgElement = function(tagName, attributes) {
53
		if (svgTags.indexOf(tagName) === -1) {
54
			throw new InvalidArgumentException(tagName, 'is not a valid SVG element');
55
		}
56

    
57
		var element = document.createElementNS('http://www.w3.org/2000/svg', tagName);
58
		for (let key in attributes) {
59
			element.setAttribute(key, attributes[key]);
60
		}
61

    
62
		return element;
63
	};
64

    
65
	/**
66
	 * Creates a new DOM node containing the text.
67
	 * 
68
	 * @param {string} text Text to create the element for.
69
	 */
70
	this.createTextElement = function(text) {
71
		return document.createTextNode(text);
72
	};
73
}
(2-2/3)