0

Easier to explain with simple code:

$("#element").fadeOut(); // jQuery; works as expected

I want to use .fadeOut() and select element with JS like this:

document.getElementById("element").fadeOut(); // Does not work

How do I make this work and is there any point of doing this (performance wise)?

Any thought is appreciated. Thanks.

tipos
  • 260
  • 2
  • 12
  • 1
    jQuery methods expect a jQuery Object in order to work. E.g. `$()` See more info about them here https://stackoverflow.com/questions/6445180/what-is-a-jquery-object – ProEvilz Jan 09 '19 at 03:01

3 Answers3

1

You can wrap the element in $():

$(document.getElementById("element")).fadeOut();

However, you may find it's easier just to use the jQuery ID selector #:

$('#element').fadeOut();
Obsidian Age
  • 39,491
  • 10
  • 44
  • 66
1

You can assign the fadeOut property name to HTMLElement.prototype, and call jQuery's fadeOut from inside it:

// $("#element").fadeOut(); // jQuery; works as expected

HTMLElement.prototype.fadeOut = function(...args) {
  $(this).fadeOut(...args);
}

document.getElementById('element').fadeOut();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element">text</div>

That said, overwriting built-in objects like HTMLElement is pretty bad practice and can cause problems - it would be better to just do what you were doing originally, and call .fadeOut on a jQuery object containing the desired element(s).

CertainPerformance
  • 313,535
  • 40
  • 245
  • 254
0

If you want to use JQuery features, you need to use $() to call the method i.e. fadeout(). See JQuery Selector.

Now that if you want to do it in vanilla JavaScript then check this out.

holydragon
  • 4,911
  • 4
  • 30
  • 45