<script type="text/javascript">
function countChildren(){
var ul = document.getElementById("myList");
alert(ul.children.length); //3 in all browsers
}
</script>
<script type="text/javascript">
function getAllElements(){
var elements = document.getElementsByTagName("*");
//12 in most browsers, 15 in IE because it includes comments
console.log(elements.length);
console.log(elements[4].outerHTML);
}
</script>
<script type="text/javascript">
if (document.querySelector){
//get the body element
var body = document.querySelector("body");
console.log(body.tagName);
//get the element with the ID "myDiv"
var myDiv = document.querySelector("#myDiv");
console.log(myDiv);
//get first element with a class of "selected"
var selected = document.querySelector(".selected");
console.log(selected.innerHTML);
//get first image with class of "button"
var img = document.body.querySelector("img.button");
console.log(img);
} else {
console.log("Selectors API not supported in this browser");
}
</script>
<script type="text/javascript">
if (document.querySelectorAll){
//get all <em> elements in a <div> (similar to getElementsByTagName("em"))
var ems = document.getElementById("myDiv").querySelectorAll("em");
console.log(ems.length);
//get all elements with class of "selected"
var selecteds = document.querySelectorAll(".selected");
console.log(selecteds.length);
//get all <strong> elements inside of <p> elements
var strongs = document.querySelectorAll("p strong");
console.log(strongs.length);
} else {
console.log("Selectors API not supported in this browser");
}
</script>
<script type="text/javascript">
function matchesSelector(element, selector){
if (element.matchesSelector){
return element.matchesSelector(selector);
} else if (element.msMatchesSelector){
return element.msMatchesSelector(selector);
} else if (element.mozMatchesSelector){
return element.mozMatchesSelector(selector);
} else if (element.webkitMatchesSelector){
return element.webkitMatchesSelector(selector);
} else {
throw new Error("Not supported.");
}
}
if (matchesSelector(document.body, "body.page1")){
alert("It's page 1!");
}
</script>