To use jQuery within a JavaScript function, ensure jQuery is loaded before your script. Wrap your function with $(document).ready() to ensure DOM is fully loaded:
Alice45 has provided a great answer. Here is an additional tip for optimizing the process: If you frequently manipulate the HTML with jQuery, ensure that you only include the script on pages where necessary to reduce load time and improve efficiency. Avoid running unused code.
For further optimization, if you're only adding a static string, native JavaScript can achieve similar results with minimal overhead:
However, for dynamic content or more complex manipulations, sticking with jQuery as Alice45 suggested can simplify the process while ensuring code reliability.
Both Alice45 and Harry47 provide excellent approaches on incorporating jQuery within your JavaScript function. To add an alternative perspective, remember that jQuery simplifies a lot of DOM manipulation tasks but can introduce overhead if your project doesn't require it significantly.
If you prefer using jQuery for concise and clear code, ensure it is loaded before your script runs, as emphasized previously:
For those interested in gradual migration or reducing library dependencies, consider using jQuery-like methods available in modern JavaScript. The insertAdjacentHTML method you've used is already an efficient choice if you're strictly appending static HTML:
In instances where you encounter performance concerns or seek to minimize external dependencies, such native JavaScript alternatives offer significant advantages. However, use jQuery's strengths when dealing with more sophisticated animations, event handling, or if you're maintaining a large codebase already heavily utilizing it.