get element by id in Jquery
Get Element by ID in jQuery
jQuery is a popular JavaScript library that simplifies HTML document traversing, event handling, and manipulation. It provides various methods to select, manipulate, and traverse HTML elements.
The jQuery ID Selector
The jQuery $("#id")
selector is used to select elements with a specified ID. It is similar to the native JavaScript document.getElementById()
method.
Here's an example:
<div id="myDiv">Hello World!</div>
<script>
// Get the element with ID "myDiv"
var myDiv = $("#myDiv");
console.log(myDiv.text()); // Output: Hello World!
</script>
The JavaScript getElementById() Method
The native JavaScript document.getElementById()
method can also be used to get an element by its ID.
Here's an example:
<div id="myDiv">Hello World!</div>
<script>
// Get the element with ID "myDiv"
var myDiv = document.getElementById("myDiv");
console.log(myDiv.textContent); // Output: Hello World!
</script>
Using highlight.js for Syntax Highlighting
highlight.js is a client-side syntax highlighting library that can be used to make code snippets look better. It supports a wide range of programming languages and markup formats.
To use highlight.js, you need to include its stylesheet and JavaScript files in your HTML document:
<!-- Include the stylesheet -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/styles/default.min.css">
<!-- Include the JavaScript file -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/highlight.min.js"></script>
Next, you need to call the hljs.highlightBlock()
method to highlight the code inside a <code>
tag:
<div id="myDiv">Hello World!</div>
<pre><code class="javascript">
// Get the element with ID "myDiv"
var myDiv = $("#myDiv");
console.log(myDiv.text()); // Output: Hello World!
</code></pre>
<script>
// Call hljs.highlightBlock() to highlight the code
hljs.highlightBlock(document.querySelector("pre code"));
</script>
Make sure to specify the language class in the <code>
tag, as highlight.js uses it to determine which syntax to highlight.