Skip to main content

Don't modify element HTML directly

Medium
Clean codeTypescriptJavaScriptSeparation of Concerns (SoC)

Use the Web API for better maintenance and testing

Examples

Example 1:

Negative

Incorrect implementation that violates the practice.

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<style>
.red {
color: red;
}
</style>
<script>
function changeMyTextColor() {
let div = document.getElementById("my-text");
div.style.color = "pink";
}
</script>
</head>
<body>
<div id="my-text" class="red">My text</div>
<button onclick="changeMyTextColor()" type="submit">Change my color</button>
</html>