Communicating with HTML (HTML Communication) is an important part of changing the content and attributes of components on a web page. JavaScript provides methods and APIs to access and manipulate HTML components such as tags, classes, or IDs.
To access an HTML component in JavaScript, we can use methods like getElementById(), getElementsByClassName(), getElementsByTagName(), or querySelector().
document.getElementById('idCuaThanhPhan');
document.getElementsByClassName('lopCuaThanhPhan');
document.getElementsByTagName('tenThe');
document.querySelector('selectorCSS');
Here is an example of accessing an HTML element:
let myElement = document.getElementById('myElement');
In the example above, we used the getElementById() method to retrieve an HTML element with the ID 'myElement'. The result is that we receive an object representing that component.
After accessing an HTML component, we can change its content and attributes.
innerHTML: This property allows you to read or change the HTML content inside an element.
let myElement = document.getElementById('myElement');
myElement.innerHTML = 'Ná»™i dung má»›i';
innerText or textContent: This property allows you to read or change the text content inside an element.
let myElement = document.getElementById('myElement');
myElement.innerText = 'Văn bản mới';
setAttribute(): This method allows you to change the value of an attribute in a component.
let myElement = document.getElementById('myElement');
myElement.setAttribute('class', 'newClass');
style: This property allows you to change the CSS properties of a component.
let myElement = document.getElementById('myElement');
myElement.style.color = 'red';
myElement.style.fontSize = '20px';
Here are some examples of communicating with HTML in JavaScript:
// Truy cáºp thà nh phần HTML
let myElement = document.getElementById('myElement');
// Thay đổi nội dung HTML
myElement.innerHTML = 'Ná»™i dung má»›i';
// Thay đổi nội dung văn bản
myElement.innerText = 'Văn bản mới';
// Thay đổi thuá»™c tÃnh
myElement.setAttribute('class', 'newClass');
// Thay đổi các thuá»™c tÃnh CSS
myElement.style.color = 'red';
myElement.style.fontSize = '20px';