html 如何输出从用户给定的ID元素开始的DOM元素列表?

rqenqsqc  于 2023-05-21  发布在  其他
关注(0)|答案(1)|浏览(132)

有一个JS函数,给我一个DOM树的列表,我需要让用户输入ID,这将是第一个输出列表,没有DOM对象从列表之前,它应该被打印。我不知道该怎么做。
我想从prompt中获取Id(div 1/image 1/parag 1...)并将其用作参数,但我不知道如何在代码中实现它。

function DOMTree(e, ul = document.getElementById('tree')) {
  for (let i = 0; i < e.childNodes.length - 1; i++) {
    if (e.childNodes[i].id != 'tree') {
      let li = document.createElement('li');
      let el = e.childNodes[i];

      if (e.childNodes[i].id != undefined) {
        li.innerText = e.childNodes[i].nodeName + ' ' + e.childNodes[i].id;
        ul.append(li);
      }

      let ul1 = document.createElement('ul');
      DOMTree(e.childNodes[i], ul1);
      ul.append(ul1);
    }
  }
}

function buttonF() {
  DOMTree(document.body);
  var input = prompt("From which element do you want to show DOM?");
  document.getElementById(input);

  input = document.getElementById();
  document.getElementById(input)
}
<body>

  <div id="div1">
    <h2 id="header1">
      Simple text, nothing special.
    </h2>

    <p id="parag1"> Тext of parag1.</p>

    <img id="image1" src='img/cactus.png' width="150"><br>
  </div>

  <div id="div2">
    <h2 id="header2">Still same text.</h2>

    <p id="parag2">Text of parag2.</p>

    <img id="image2" src="img/sunflower.png" width="150"> <br>
  </div>

  <ul id="idList"></ul>

  <button id="button1" onclick="buttonF()">Show the DOM tree:</button><br><br>
  <script src="jscode.js"></script>

</body>
pepwfjgg

pepwfjgg1#

你差点就成功了。
首先,您需要从提示符中获取输入。然后将其作为第一个参数传递到getElementById中,然后将目的地作为第二个参数。

function buttonF(){
  var input = prompt("From which element do you want to show DOM?");
  DOMTree(document.getElementById(input),document.querySelector("#idList"));
}
function DOMTree(e, ul = document.getElementById('tree')) {
  for (let i = 0; i < e.childNodes.length - 1; i++) {
    if (e.childNodes[i].id != 'tree') {
      let li = document.createElement('li');
      let el = e.childNodes[i];
      if (e.childNodes[i].id != undefined) {
        li.innerText = e.childNodes[i].nodeName + ' ' + e.childNodes[i].id;
        ul.append(li);
      }
      let ul1 = document.createElement('ul');
      DOMTree(e.childNodes[i], ul1);
      ul.append(ul1);
    }
  }
}

function buttonF(){
  var input = prompt("From which element do you want to show DOM?").replace("#","");
  DOMTree(document.getElementById(input),document.querySelector("#idList"));
}
<div id="div1">
        <h2 id="header1">
            Simple text, nothing special.
        </h2>

        <p id="parag1"> Тext of parag1.</p>

        <img id="image1" src = 'img/cactus.png' width="150"><br>

        </div>

        <div id="div2">
        <h2 id="header2"> 
            Still same text. 
        </h2>

        <p id="parag2">Text of parag2.</p>

        <img id="image2" src ="img/sunflower.png" width="150"> <br>

        </div>

    <ul id="idList"></ul>
    

    <button id = "button1" onclick = "buttonF()">Show the DOM tree:</button><br><br>

相关问题