try this
var message = document.getElementById('helloWorld');
message.innerHTML='<del>helloworld</del>'
Frage
I want to strike through text in Javascript but I can't seem to get the code to work.
var message = document.getElementById('helloWorld');
setTextContent(message, 'hello world!'.strike());
Would appreciate any help. Would also like to do it without using css.
Should Also mention that these lines of code are inside another function called totalPackage() which runs when the user clicks a button. I want my message hello world! to be displayed when this other function is called.
Lösung 2
try this
var message = document.getElementById('helloWorld');
message.innerHTML='<del>helloworld</del>'
Andere Tipps
Using Unicode Character 'COMBINING LONG STROKE OVERLAY' (U+0336)
E̶x̶a̶m̶p̶l̶e̶
function strikeThrough(text) {
return text
.split('')
.map(char => char + '\u0336')
.join('')
}
<input oninput="document.querySelector('#output').innerText = strikeThrough(this.value)" placeholder="type here"><p id="output"></p>
To undo it, simply remove all the \u0336
characters from the string.
string.replace(/[\u0336]/g, '')
The right syntax of strike()
is str.strike()
so use like
setTextContent(message, 'hello world!'.strike());
If #helloWorld
is a DIV, then you can set its innerHTML property.
<div id="helloWorld"></div>
function setTextContent(msg, str) {
msg.innerHTML = str;
}
var message = document.getElementById('helloWorld');
setTextContent(message, 'hello world!'.strike());
Here's a fiddle to demonstrate: http://jsfiddle.net/SXFLw/
If you would like to do it respective to the format in you question, you can make a string prototype method to handle it. String.strike()
is non standard and you may run into browser compatibility issues.
String.prototype.strike = function() {
return '<div class="strike">'+ this +'</div>';
};
// <div class="strike"> hello world! </div>
var test = 'hello world!'.strike();
Then in CSS you can make a class named strike
like so.
.strike {
text-decoration: line-through;
}
There's already a strike
method in JavaScript, however it seems to be non-standard.
The normal implementation simply wraps the string in a strike
tag. However, please note that the result isin't simple text anymore, so setting the textContent
propert of a text node to 'some string'.strike()
would not give the expected result. It would just display the markup as plain text in the document.
You could always implement a polyfill, like:
if (!(typeof String.prototype.strike === 'function')) {
String.prototype.strike = function () {
return '<strike>' + this + '</strike>';
};
}