getAttribute và setAttribute trong Javascript [JAVASCRIPT]
Hôm nay ta sẽ học 1 cách khác để lấy ra 1 attribute của 1 thẻ. Những bài viết trước ta dùng như sau
<a id="myLink" href="http://dblog24h.com">Click me</p>
<script>
var link = document.getElementById('myLink');
// Get href
console.log(link.href); // http://dblog24h.com
// Set href
link.href = "http://google.com";
console.log(link.href); // http://google.com
</script>
Hôm nay ta sẽ dùng getAttribute để lấy ra attribute của thẻ và setAttribute để thêm attribute cho thẻ.
<a id="myLink2" href="http://dblog24h.com">Click me</p>
<script>
var link = document.getElementById('myLink2');
// Get href
console.log(link.getAttribute); // http://dblog24h.com
// Set href
link.setAttribute("href", "http://google.com");
console.log(link.getAttribute); // http://google.com
// Check attribute
console.log(link.hasAttribute("href")); // true
console.log(link.hasAttribute('abc')); // false
// removeAttribute
link.removeAttribute('href');
</script>
Ngoài getAttribute và setAttribute ta cũng có phương thức check attribute như hasAttribute, phương thức này return true nếu có attribute đó, còn return false khi không có. Phương thức removeAttribute dùng để xoá attribute cho thẻ.