document.createAttribute() example
RUN
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style type="text/css"> #test { color: red; } </style> <body> <h1>Học lập trình miễn phí tại freetuts.net</h1> <p id="result"></p> <button onclick="myFunction()">Xem kết quả</button> <script> function myFunction(){ var h1 = document.getElementsByTagName("H1")[0]; // lấy phần tử h1 var att = document.createAttribute("id"); // tạo thuộc tính id att.value = "test"; // gán giá trị cho thuộc tính id h1.setAttributeNode(att); // gắn thuộc tính id với giá trị cho thẻ h1 } </script> </body> </html>
PHÓNG TO