Chào bạn! Trong quá trình làm việc với jQuery, một trong những thao tác phổ biến nhất là lấy (get) và gán (set) nội dung HTML hoặc các thuộc tính (attributes) của phần tử. Bài viết này sẽ giúp bạn hiểu rõ cách sử dụng các hàm jQuery như .html(), .text(), .val(), và .attr() để làm chủ việc tương tác DOM.
1. Lấy (Get) nội dung HTML và text
.html()
- Công dụng: Lấy nội dung HTML bên trong một phần tử (bao gồm cả thẻ HTML).
let content = $("#demo").html();
console.log(content);Ví dụ: Nếu <div id="demo"><b>Hello</b></div> → kết quả là "<b>Hello</b>"
.text()
- Công dụng: Lấy nội dung chỉ text, loại bỏ tất cả thẻ HTML.
let text = $("#demo").text();
console.log(text);Với phần tử như trên, kết quả sẽ là "Hello"
.val()
- Công dụng: Dùng với các input field để lấy giá trị người dùng nhập vào.
let name = $("#nameInput").val();
console.log(name);Dành cho <input id="nameInput" value="John"> → kết quả là "John"
2. Gán (Set) nội dung HTML, Text, và Value
.html("...")
- Thay thế nội dung HTML của phần tử.
$("#demo").html("<i>Xin chào!</i>");.text("...")
- Gán nội dung dạng văn bản (sẽ không hiểu thẻ HTML).
$("#demo").text("<i>Không in nghiêng</i>");.val("...")
- Dùng để gán giá trị cho input field.
$("#nameInput").val("CodeTutHub");3. Lấy và Gán thuộc tính (Attributes)
.attr("ten-thuoc-tinh") – Get
let link = $("#myLink").attr("href");.attr("ten-thuoc-tinh", "gia-tri") – Set
$("#myLink").attr("href", "https://codetuthub.com");4. Ví dụ
Learn Python syntax easily with this beginner-friendly guide. Understand basic syntax rules, variables, loops,...
Struggling with the “Key is already in use” error when adding an SSH key to GitHub? This guide walks you through the...
Learn how to get URL segments in Laravel using Request::segment() and segments() methods. Step-by-step examples and best...
Struggling with the “Key is already in use” error when adding an SSH key to GitHub? This guide walks you through the...
Learn how to clear cache in Laravel 12 for Routes, Views, Config, Events, and more. Detailed guide on Artisan commands...
Learn how to install Python quickly and easily with this step-by-step guide for Windows, macOS, and Linux. Start your...
Learn Python syntax easily with this beginner-friendly guide. Understand basic syntax rules, variables, loops,...
Learn how to use CSS offset-path, offset-position, offset-distance, and offset-rotate properties to create smooth and...
