Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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'>
question from:https://stackoverflow.com/questions/65661280/striking-the-input-text-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
69 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...