Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

javascript - Removing a class from value in an <input> tag

I have an <input> tag with some HTML as the value. I want to remove any <span>s that have the class of "emphasis", but still retain the content in the <span>. I also don't want any other <span>s removed.

Example Below:

This:

<input type="hidden" name="answer" id="answer" value="<span class="emphasis"><div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div></span>"

should end up as:

<input type="hidden" name="answer" id="answer" value="<div class="fraction_display"><span class="numer_display">21</span><span class="bar_display">/</span><span style="border-top-color: green;" class="denom_display">23</span></div>"`

I've tried using jQuery with this fiddle (https://jsfiddle.net/0xgx04pq/4/)...

function remove_emphasis_class (){
  var content = $('#answer').val(answer);
  var content_after = content.filter('span.emphasis').contents().unwrap();
  $('#answer').val(content_after);
  alert(content_after);
}
.emphasis {
  background: orange;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="hidden" value="2 + 5 = <span class='emphasis'>7</span>" name="answer" id="answer">
<br><br>
<button onclick="remove_emphasis_class();">Remove Class</button>
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Basic idea

//using string instead of reading value of the input aka var str = $(".foo").val();
var str = "2 + 5 = <span class='emphasis'>7</span>";
//convert the string to html
var temp = $("<div>").html(str);
//find the span and unwrap it
temp.find(".emphasis").contents().unwrap();
//get the html string without the span
var updated = temp.html();
//display it
console.log(updated);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...