hw_15_05_get.html 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <header>
  2. GetElementById Throw
  3. </header>
  4. <body>
  5. <div id="xId">
  6. <div id="testId">testDiv</div>
  7. </div>
  8. <script>
  9. const getElementById = (parent, id) => {
  10. try {
  11. walker(parent, id);
  12. return null;
  13. }
  14. catch (e) {
  15. if (e.message == "Element found.")
  16. return e.result;
  17. else
  18. throw e;
  19. }
  20. }
  21. function walker(parent, id) {
  22. let isObject = true;
  23. if (Array.isArray(parent)) {
  24. }
  25. else if (parent != null && typeof parent === "object") {
  26. if (parent.id == id) {
  27. let err = new Error("Element found.");
  28. err.result = parent;
  29. throw err;
  30. }
  31. }
  32. else
  33. isObject = false;
  34. if (isObject) {
  35. for (child of parent.children) {
  36. walker(child, id);
  37. }
  38. }
  39. }
  40. var children = xId.children;
  41. var val = xId.value;
  42. el = getElementById(document.body, "testId");
  43. alert(el.innerText);
  44. </script>
  45. </body>