-1

Here is my selector in native JavaScript:

const textarea = document.getElementsByTagName("textarea")[0];

What is the equivalent in jQuery?

I have tried this with no luck:

const textarea = $("textarea")[0];

Here is another example:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".btn1").click(function(){
  
    const textarea = $("p")[0];
    textarea.fadeOut();
    
  });
  $(".btn2").click(function(){
    $("p").fadeIn();
  });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>

<button class="btn1">Fade out</button>
<button class="btn2">Fade in</button>

</body>
</html>
foxer
  • 811
  • 1
  • 6
  • 16
  • 1
    That **is** the equivalent. https://jsbin.com/puwozokaca/1/edit?js,console We've no way of telling why you had no luck with it. You haven't provided a [mcve]. – Quentin May 19 '20 at 18:25
  • please look at the edit.. – foxer May 19 '20 at 18:27
  • You're trying to call `fadeOut` on it. There's no fadeOut method on a DOM element. You'd get the same error if you tried `const textarea = document.getElementsByTagName("p")[0];` – Quentin May 19 '20 at 18:27
  • exactly... I want to select the first element by its tag using jQuery... that's what I asked... – foxer May 19 '20 at 18:29
  • @ Quentin BenM's answer is the solution... – foxer May 19 '20 at 18:31
  • Duplicate of https://stackoverflow.com/questions/2173971/jquery-find-to-get-the-first-element – str May 19 '20 at 18:55

2 Answers2

1

The console tells you what the problem is:

Uncaught TypeError: textarea.fadeOut is not a function

fadeOut and similar jQuery functions must be called on a jQuery object. When you access a jQuery object through array notation (i.e. $('textarea')[0]), you actually get a DOMElement.

If you want the first element of a specific type as a jQuery object, use eq() or first():

$(".btn1").click(function() {
  const textarea = $("p").first();
  textarea.fadeOut();    
});

$(".btn2").click(function(){ $("p").fadeIn(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>This is a paragraph.</p>

<button class="btn1">Fade out</button>
<button class="btn2">Fade in</button>
BenM
  • 52,573
  • 26
  • 113
  • 168
1

Here is your working example. eq() let you specify the index of the element you are trying to get.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $(".btn1").click(function(){
  
    const textarea = $("p:eq(0)");
    textarea.fadeOut();
    
  });
  $(".btn2").click(function(){
    $("p").fadeIn();
  });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>

<button class="btn1">Fade out</button>
<button class="btn2">Fade in</button>

</body>
</html>
lidermin
  • 2,782
  • 11
  • 43
  • 48