When working with the value
attribute of an input
element in JavaScript, it can be a bit challenging to apply styles to different parts of the input value. However, there is a creative solution that involves splitting the value into two words and styling them separately.
By using JavaScript to split the string into an array of words, you can then use CSS to apply strike-through to the first word with text-decoration: line-through
, and keep the second word unaffected with text-decoration: none
.
While this approach may not be ideal for production environments, it is possible to achieve the desired effect by creating two span
elements to display each word individually. By setting the original input value's text color to transparent and positioning the span
elements accordingly, you can create the visual appearance of strike-through on the first word and plain text on the second word within the input field.
const textBlot = document.querySelector(".text-blot");
const demo = document.querySelector(".demo");
const word1 = document.createElement("span");
const word2 = document.createElement("span");
word1.setAttribute("class", "strike");
word2.setAttribute("class", "no-strike");
demo.appendChild(word1);
demo.appendChild(word2);
const arr = textBlot.value.split(" "); // create an array of words
word1.innerHTML = arr[0];
word2.innerHTML = " " + arr[1];
.text-blot {
/* text-decoration: line-through; */
z-index: 1;
color: transparent;
}
.strike {
text-decoration: line-through;
}
.no-strike {
text-decoration: none;
}
.demo span {
position: relative;
left: -9.5rem;
z-index: 99;
}
<div class="demo">
<input type='text' value='two words' class='text-blot'>
</div>