This question already has answers here:
How does NextSibling work?
                                
                                    (2个答案)
                                
                        
                2年前关闭。
            
        

在此示例中,我想获取2个先前同级的值

但这不起作用btn.previousSibling.previousSibling.value

我需要使用4 previousSibling来获取值,为什么是4?

<!DOCTYPE HTML>
<html>
<head>
<script>
function text(btn){
    console.log(btn.previousSibling.previousSibling.previousSibling.previousSibling.value)
}
</script>
</head>
<body>
    <textarea></textarea>
    <br>
    <button onclick="text(this)">text</button>
</body>
</html>

最佳答案

previousSibling指向上一个Node,在您的示例中是新行(TextNode)。您可能要使用previousElementSibling代替



function text(btn){
  console.log(
    btn
      .previousElementSibling
      .previousElementSibling
      .value
  );
}

<textarea>Hello</textarea>
<br>
<button onclick="text(this)">text</button>

07-28 08:25