Javascript Reference - HTML DOM Code Object








The Code object represents an HTML <code> element.

Example

The following code gets a <code> element by using getElementById().


<!DOCTYPE html>
<html>
<body>
<code id="myCode">button</code>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--  w w  w .  j a v  a  2 s . co  m-->
    var x = document.getElementById("myCode");
    x.style.color = "blue";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code create a <code> element by using the document.createElement() method:


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button><br><br>
<script>
function myFunction() {<!--   w  w  w  .  ja va 2 s  .  co m-->
    var x = document.createElement("CODE");
    var t = document.createTextNode("code test");
    x.appendChild(t);
    document.body.appendChild(x);
}
</script>
</body>
</html>

The code above is rendered as follows:





Standard Properties and Events

The Code object also supports the standard properties and events.