'innerHTML 을 쓰지 말고 createElement 로 사용해라.'에 해당되는 글 1건

  1. 2010.11.22 innerHTML 을 쓰지 말고 createElement 로 사용해라.
반응형

2.2 Dynamic content generation

This technique relates to the following sections of the guidelines:

Task:

Avoid document.write() and innerHTML().

Assistive technologies such as screen readers rely on the Document Object Model (DOM) to interpret the semantics in HTML for a different modality. Given this, the document.write() and innerHTML() methods can render content invalid (and inaccessible via DOM) after the fact.

Deprecated Example:

This deprecated example shows a script that inserts a header, a paragraph (which is unterminated, and thus invalid), and a list (again, invalid) into a given document.

 
function fillContent() {
	document.write("<h1>Welcome to my site</h1>");
	document.write("<p>Lorem ipsum dolor sit amet");
	document.menu.innerHTML = "<ul><li><a href="foo.html">foo</a>";
}

Example:

The following code sample does the same as the example above, but produces valid code which appears in the HTML document's DOM tree:

 
function fillContent() {
	// parentelem is a specified element in the DOM
	var header = document.createElement("h1");
	header.insertText("Welcome to my site");
	var para = document.createElement("p");
	para.insertText("Lorem ipsum dolor sit amet");
	var list = document.createElement("ul");
	itemone = document.createElement("li");
	itemonelink = document.createElement("a");
	itemonelink.setAttribute("href","foo.html");
	itemonelink.insertText("foo");
	list.appendChild(itemone);
	parentelem.appendChild(header);
	parentelem.appendChild(para);
	parentelem.appendChild(list);
}

Editorial Note: Two issues have been raised with this example what happens to XSL on server-side and how does this effect XPointers (and RDF-based accessibility).

Posted by 1010