
Html And Css in Jquery
In jQuery, you can easily manipulate HTML and CSS of elements using built-in methods. This makes it super handy for dynamically changing content and styles on your web page.
? 1. HTML Manipulation in jQuery
? .html()
– Get or Set HTML content
var text = $("#box").text();// Set text content$("#box").text("This is just plain text");
? .append()
/ .prepend()
– Add HTML
$("#box").append("<p>Appended text</p>");$("#box").prepend("<p>Prepended text</p>");
? .after()
/ .before()
– Insert HTML around element
$("#box").after("<p>After the box</p>");$("#box").before("<p>Before the box</p>");
? 2. CSS Manipulation in jQuery
? .css()
– Get or Set CSS styles
? Set a single CSS property:
$("#box").css("color", "red");
? Set multiple CSS properties:
$("#box").css({ "background-color": "yellow", "font-size": "20px"});
? Get the value of a CSS property:
var color = $("#box").css("color");
? Example: HTML + CSS with jQuery
<!DOCTYPE html>#box { padding: 20px; border: 2px solid black; width: 300px; } </style> "#changeContent").click(function() { $("#box").html("<b>New HTML content!</b>"); }); $("#changeStyle").click(function() { $("#box").css({ "background-color": "lightblue", "color": "darkblue", "font-size": "18px" }); });</script></body></html>
? Summary of Common Methods
jQuery Method | Description |
---|---|
.html() | Get/Set HTML content |
.text() | Get/Set plain text |
.css() | Get/Set CSS properties |
.append() | Add content inside element (end) |
.prepend() | Add content inside element (start) |
.after() | Insert content after element |
.before() | Insert content before element |