Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thay thế khoảng trắng trong các phần tử cùng class bằng JavaScript


Sử dụng ký hiệu class (.) kết hợp each() để duyệt và thay thế.

Ví dụ

Mã thực hiện:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <title>Document</title> 
</head> 
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> 
<script src="https://code.jquery.com/jquery-1.12.4.js"></script> 
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 
<body> 
  <p class="demo">Javascript Tutorial</p> 
  <p class="demo">MySQL Tutorial</p> 
  <p class="demo">MongoDB Tutorial</p> 
</body> 
<script> 
  $(".demo").each(function (i, element) { 
    $(element).html($(element).html().split(" ").join("")); 
  }); 
</script> 
</html>

Mở file bằng Live Server.

Kết quả

Hình ảnh minh họa kết quả.