Table of Contents
ToggleJquery Get
jQuery DOM Manipulation
jQuery is a powerful JavaScript library that provides a wide range of methods for DOM (Document Object Model) manipulation. With jQuery, you can easily select elements, modify their attributes, add or remove content, and manipulate the CSS styles of the page.
Here are some common jQuery methods for DOM manipulation:
- Selecting Elements: jQuery provides several selectors for selecting elements, including element selectors, class selectors, ID selectors, attribute selectors, and more. The most basic selector is the element selector, which selects all elements of a given type. To illustrate, if you wish to choose every paragraph on a webpage, employing the subsequent code would be effective:
$("p")
Modifying Attributes: Once you’ve selected an element, you can use jQuery methods to modify its attributes. For example, to change the text of a paragraph element, you can use the text() method:
$("p").text("New text");
To change the value of an input element, you can use the val() method:
$("input").val("New value");
Adding or Removing Content: jQuery provides several methods for adding or removing content from the page. For example, to add a new paragraph element to the page, you can use the append() method:
$("body").append("<p>New paragraph</p>");
To remove an element from the page, you can use the remove() method:
$("p").remove();
Manipulating CSS Styles: jQuery provides several methods for manipulating the CSS styles of the page. As an illustration, to modify the background color of a page element, employ the css() method:
$("p").css("background-color", "red");
To add or remove a CSS class from an element, you can use the addClass() or removeClass() method:
$("p").addClass("highlight"); $("p").removeClass("light");
Among the myriad jQuery methods for manipulating the Document Object Model, these are merely a glimpse. jQuery empowers you to effortlessly craft dynamic and interactive web pages, often requiring just a handful of code lines.
Get(Jquery Get) Content – text(), html(), and val()
Three simple, but useful, jQuery methods for DOM manipulation are:
text() – Sets or returns the text content of selected elements
html() – Sets or returns the content of selected elements (including HTML markup)
val() – Sets or returns the value of form fields
The following example demonstrates how to get content with the jQuery text() and html() methods:
$("#btn1").click(function(){ alert("Text: " + $("#test").text()); }); $("#btn2").click(function(){ alert("HTML: " + $("#test").html()); });
Get(Jquery Get) Attributes – attr()
The jQuery attr() method is used to get attribute values.
Jquery Get: The following example demonstrates how to get the value of the href attribute in a link:
$("button").click(function(){ alert($("#w3s").attr("href")); });