Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a strikethrough text using JavaScript?
To create a strikethrough text with JavaScript, you can use several methods. The legacy strike() method wraps text in deprecated <strike> tags, while modern approaches use CSS styling for better compatibility.
Using the Legacy strike() Method
The strike() method creates strikethrough text by wrapping it in <strike> tags. However, this method is deprecated and not recommended for new projects.
<html>
<head>
<title>JavaScript String strike() Method</title>
</head>
<body>
<script>
var str = "Demo Text";
document.write(str.strike());
console.log(str.strike()); // Shows the HTML: <strike>Demo Text</strike>
</script>
</body>
</html>
<strike>Demo Text</strike>
Modern Approach: Using CSS text-decoration
The recommended method is to apply CSS styling directly using JavaScript:
<html>
<head>
<title>Modern Strikethrough Text</title>
</head>
<body>
<p id="demo">This text will be struck through</p>
<button onclick="addStrikethrough()">Add Strikethrough</button>
<button onclick="removeStrikethrough()">Remove Strikethrough</button>
<script>
function addStrikethrough() {
var element = document.getElementById("demo");
element.style.textDecoration = "line-through";
}
function removeStrikethrough() {
var element = document.getElementById("demo");
element.style.textDecoration = "none";
}
</script>
</body>
</html>
Dynamic Text Creation
You can also create strikethrough text dynamically by setting innerHTML with CSS:
<html>
<head>
<title>Dynamic Strikethrough</title>
</head>
<body>
<div id="output"></div>
<script>
function createStrikethroughText(text) {
return '<span style="text-decoration: line-through;">' + text + '</span>';
}
var output = document.getElementById("output");
output.innerHTML = createStrikethroughText("This text is struck through");
</script>
</body>
</html>
Comparison
| Method | Browser Support | Recommended | Notes |
|---|---|---|---|
strike() method |
Legacy support | No | Deprecated, uses obsolete <strike> tag |
| CSS text-decoration | All modern browsers | Yes | Standard approach, flexible styling |
| Dynamic innerHTML | All modern browsers | Yes | Good for creating new content |
Conclusion
While the strike() method exists for legacy compatibility, use CSS text-decoration: line-through for modern strikethrough text. This approach provides better browser support and follows current web standards.
