<!DOCTYPE html>
<title>テキストノードを含まない、子要素を探る関数を書く</title>
<meta charset="UTF-8"/>
<style>
textarea {
font-size: small;
}
</style>
<body>
<h1>テキストノードを含まない、子要素を探す</h1>
<p>
基本というか、元が高度なのだけれど。<br>
<textarea cols="100" rows="36">
(function (proto, getElement) {
proto.__defineGetter__ ('firstElementChild', function () {
return getElement.call (this, 'firstChild', 'nextSibling');
});
proto.__defineGetter__ ('lastElementChild', function () {
return getElement.call (this, 'lastChild', 'previousSibling');
});
proto.__defineGetter__ ('previousElementSibling', function () {
return getElement.call (this, 'previousSibling');
});
proto.__defineGetter__ ('nextElementSibling', function () {
return getElement.call (this, 'nextSibling');
});
proto.__defineGetter__ ('childElementCount', function () {
for (var count = 0, n = this.firstElementChild; n; n = n.nextElementSibling, count++);
return count;
});
} )(
Element.prototype,
function (start, direction) {
for (var node = this[start]; node; node = node[direction || start]) {
if (node.nodeType == Node.ELEMENT_NODE) {
break;
}
}
return node;
}
);
</textarea>
<p>
Object.create () を使って書き直す。<br>
<textarea cols="100" rows="36">
(function (getElement) {
Object.create (Element.prototype, {
firstElementChild : {
get :
function () {
return getElement.call (this, 'firstChild', 'nextSibling');
}
},
lastElementChild : {
get :
function () {
return getElement.call (this, 'lastChild', 'previousSibling');
}
},
previousElementSibling : {
get :
function () {
return getElement.call (this, 'previousSibling');
}
},
nextElementSibling : {
get :
function () {
return getElement.call (this, 'nextElementSibling');
}
},
childElementCount : {
get :
function () {
for (var count = 0, n = this.firstElementChild; n; n = n.nextElementSibling, count++);
return count;
}
}
});
}) (
function (start, direction) {
for (var node = this[start]; node; node = node[direction || start]) {
if (node.nodeType == Node.ELEMENT_NODE) {
break;
}
}
return node;
}
);
</textarea>
<script>
</script>