html5的確給咱們帶來驚喜, 新增的dom api-類選擇器javascript
那麼怎樣使用呢?看下面的代碼吧.....css
JavaScript
var els = document.getElementsByClassName('myinput');
els[0].focus();
多有意思的一個api,提供了豐富的用戶體驗!html
看下面的小例子吧html5
XML/HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html5-DOM API</title>
</head>
<body>
<textarea class="section"></textarea>
<script type="text/javascript">
var els = document.getElementsByClassName('section');
els[0].focus();
</script>
</body>
</html>
經過相似 css 選擇器的語法定位元素 (Selectors API)java
JavaScript
var els = document.querySelectorAll("ul li:nth-child(odd)");
var els = document.querySelectorAll("table.test > tr > td");
api
XML/HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>html5-querySelectorAll</title>
</head>
<body>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
<script type="text/javascript">
var els = document.querySelectorAll("ul li:nth-child(odd)");
for(var i =0; i<els.length; i++)
els.item(i).style.color="#f00";
</script>
</body>
</html>
其餘的例子dom
XML/HTML
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>table</title>
</head>
<body>
<table width="200" border="1">
<tr>
<td>s</td>
<td>s</td>
<td>s</td>
<td>s</td>
</tr>
<tr>
<td>s</td>
<td>s</td>
<td>s</td>
<td>s</td>
</tr>
<tr>
<td>s</td>
<td>s</td>
<td>s</td>
<td>s</td>
</tr>
<tr>
<td>s</td>
<td>s</td>
<td>s</td>
<td>s</td>
</tr>
</table>
<script type="text/javascript">
var els = document.querySelectorAll("table tr td");
alert(els.length);
for(var i = 0; i<els.length; i++)
els.item(i).style.color="#f00";
</script>
</body>
</html> ui