Welcome ðŸŽ‰

logo

ReactLMS

Search
Light Mode
Contact Us

5 min to read

Contact us

No results for your search.
Sorry, an unexpected error occurred

Concept


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.


Accessing HTML Components


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.


Changing HTML Content and Attributes


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';







Example with Code


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';









Read more
On This Page