I am new to programming and I want to access the array inside an object using Javascript...
The data structure:
const some_obj = {
accessKey: "",
children: [
div.someclassname,
div.someclassname,
div.someclassname.highlight,
]
}
This is the output in the browser console when I log the variable:
some_obj
current: div.wrapper
accessKey: ""
align: ""
childElementCount: 4
childNodes: NodeList(4) [div.someclassname, div.someclassname.highlight,
div.someclassname]
children: HTMLCollection(4) [div.someclassname,
div.someclassname.highlight, div.someclassname]
Printing some_obj.children
in the console gives below output:
some_obj.children
HTMLCollection(3)
0: div.someclassname
1: div.someclassname.highlight
2: div.someclassname
Now, from the some_obj
I want to check if some_obj
has div.someclassname.highlight
in the children
array. How can I do that?
I tried using some_obj.current.children.find()
but it says find()
is not a function.
How can I check if the some_obj
children have the div.someclassname.highlight
?
Could someone help me fix this? Thanks.
I don’t think there is a more elegant solution for HTMLCollection
, but this works.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<style>
.selected {
font-weight: bold;
}
</style>
</head>
<body>
<ul>
<li class="test">One</li>
<li class="test">two</li>
<li class="test selected">Three</li>
</ul>
<script>
var find = function(className) {
var elements = document.getElementsByClassName('test');
var elementsArray = [].slice.call(elements);
for (var index = 0; index < elementsArray.length; index++) {
var element = elementsArray[index];
if (element.className.indexOf(className) !== -1) {
return true;
// return element; // If you wish to return the element instead of true (comment out previous line if this option is used)
}
}
return false;
// return null; // If you wish to return null instead of false (comment out previous line if this option is used)
}
console.log(find('selected'));
</script>
</body>
</html>