3

In this example, I want to get the value of 2 previous sibling

But this is not work btn.previousSibling.previousSibling.value

I need use 4 previousSibling to get the value, why 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>
CL So
  • 3,647
  • 10
  • 51
  • 95

3 Answers3

3

previousSibling points to the previous Node, which is new line (a TextNode) in your example. You might want to use previousElementSibling instead

function text(btn){
  console.log(
    btn
      .previousElementSibling
      .previousElementSibling
      .value
  );
}
<textarea>Hello</textarea>
<br>
<button onclick="text(this)">text</button>
Thum Choon Tat
  • 3,084
  • 1
  • 22
  • 24
0

It can be because of empty entries inserted by the browser :

https://developer.mozilla.org/en-US/docs/Web/API/Node/previousSibling

this code works in your case :

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

You can use JQuery $(btn).prev().prev();

Like :

<!DOCTYPE HTML>
<html>
<head>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
</script>
<script>
function text(btn){
    alert($(btn).prev().prev().val());
}
</script>
</head>
<body>
    <textarea>test text</textarea>
<br>
<button onclick="text(this)">text</button>
</body>
</html>
Coskun Ozogul
  • 2,389
  • 1
  • 20
  • 32
0

The reason is because of the br element. You can get the parent using parentNode and queryselector to get the specific element.

function text(btn) {
  var getText = btn.parentNode.querySelector('textarea').value;
  console.log(getText.trim())
}
<textarea></textarea>
<br>
<button onclick="text(this)">text</button>
brk
  • 48,835
  • 10
  • 56
  • 78