I'm trying to implement native document.getElementById in javascript. I've implemented document.getElementsByClassName in javascript.
function getElementsByClassName (className) {
var nodeList = [];
function test(node) {
if (node.classList && node.classList.contains(className)) {
nodeList.push(node);
}
for (var index = 0; index < node.childNodes.length; index++) {
test(node.childNodes[index]);
}
return nodeList;
}
test(document.body);
return nodeList;
};
// Fails here.
function getElementById(className) {
const result = [];
function getEachIDNode(node) {
if(node.contains(className)) {
return node;
}
for(let i=0; i<node.childNodes.length; i++) {
getEachIDNode(node.childNodes[i]);
}
}
getEachIDNode(document.body);
}
console.log(getElementsByClassName('winner'));
console.log(getElementById('test'));
<table>
<tr id="test">
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">aa</td>
<td>bb</td>
<td>cc</td>
<td>dd</td>
</tr>
</table>
<table>
<tr>
<td>#</td>
<td class="winner">dd</td>
<td>cc</td>
<td>bb</td>
<td>aa</td>
</tr>
</table>
I'm trying to understand how I can check if a node has an attribute ID.
Can someone enlighten me?
Check the id property of the node against the passed argument (probably better to use id as an argument rather than className):
function getElementById(id) {
const result = [];
function getEachIDNode(node) {
if(node.id === id) {
result.push(node);
}
for(let i=0; i<node.childNodes.length; i++) {
getEachIDNode(node.childNodes[i]);
}
}
getEachIDNode(document.body);
return result;
}
console.log(getElementById('subchild')[0].innerHTML);
<div id="parent">
<div id="child1">
</div>
<div id="child2">
<div id="subchild">
subchild!
</div>
</div>
</div>
But if you actually want to replicate getElementById, don't try to return an array, return a single element
:
function getElementById(id) {
let match = null;
const doFind = node => {
if (!match && node.id === id) match = node;
if (!match) return [...node.childNodes].find(doFind);
}
doFind(document.body);
return match;
}
console.log(getElementById('subchild').innerHTML);
<div id="parent">
<div id="child1">
</div>
<div id="child2">
<div id="subchild">
subchild!
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With