-1

I have a input box of type text and the input value have 2 words and I need to strike only the first word not the second one and unfortunately I can't edit html. I should do it using javascript and css only. I have tried using css text-decoration: line-through; but it striking both the words. any help is very much appreciated.

.text-blot {  text-decoration: line-through; }
<input type='text' value='two words' class='text-blot'>
prem kumar
  • 101
  • 10
  • Does this answer your question? [CSS to select/style first word](https://stackoverflow.com/questions/55612/css-to-select-style-first-word) – Manas Khandelwal Jan 11 '21 at 04:22
  • Have a look at this [Is there a way to style part of an input fields value](https://stackoverflow.com/questions/3121683/is-there-a-way-to-style-part-of-an-input-fields-value) – Tanner Dolby Jan 11 '21 at 04:32
  • that is `p` tag mine is `input` tag. i need to modify the value set to `value` attribute – prem kumar Jan 11 '21 at 04:32
  • @premkumar The link I included is specifically referring to an `input` element and its `value`. Not a `p` tag. – Tanner Dolby Jan 11 '21 at 04:41
  • @TannerDolby that comment is not for you and your answer doesn't help as it involves modifying html – prem kumar Jan 11 '21 at 04:48

1 Answers1

2

The value attribute within an input element can be accessed using JavaScript with HTMLElement.value. Unfortunately, styles will apply to the whole input value. So this is a bit tricky.

Since the value is a single string, which will contain two words. I used some JavaScript to split the string into array of words so then you can strike-through the first word using CSS with text-decoration: line-through and the second word can have text-decoration: none (no strike-through).

I wouldn't recommend this in a production environment, but I made it work by creating two span elements to hold the two words and styled them accordingly. I then gave the original input value a transparent text color with color: transparent and positioned the two span elements on top of the input value to achieve your desired first word strike-through second word without.

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>
Tanner Dolby
  • 4,253
  • 3
  • 10
  • 21