简体   繁体   中英

Remove text between two html tags using jQuery

I have the following HTML :

<span>
<input type="text" value="0" size="10" class="element text currency" readonly="readonly" name="element_18_1" id="element_18_1"> .       
<label for="element_18_1">Dollars</label>
</span>

I would like to remove the dot between the input and the label tags using jQuery.

I tried this code with no result : $('#element_18_1').contents(':gt(2)').remove(); Thanks

This removes all texts which are not inside a tag (as element)

 $(document).ready(function(){ current = $('#element_18_1'); siblings = $('#element_18_1').siblings(); parent = $('#element_18_1').parent(); $(parent).html(''); $(parent).append(current).append(siblings); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <span> <input type="text" value="0" size="10" class="element text currency" readonly="readonly" name="element_18_1" id="element_18_1"> . <label for="element_18_1">Dollars</label> </span> 

You can make it shorter by joining some lines. I tried to show it step by step

You could, however always choose an easier way, a simpler way, a clan slate readable and understandable way, a pure JavaScript way.

element_18_1.nextSibling.data=" ";

 element_18_1.nextSibling.data=" "; 
 <span> <input type="text" value="0" size="10" class="element text currency" readonly="readonly" name="element_18_1" id="element_18_1"> . <label for="element_18_1">Dollars</label> </span> 

You can use contents() and slice() , ie:

 var el1 = $("#element_18_1"), el2 = $("#element_18_1 + label"), contents = el1.parent().contents(); contents.slice(contents.index(el1) + 1, contents.index(el2)).remove(); el1.after(" "); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span> <input type="text" value="0" size="10" class="element text currency" readonly="readonly" name="element_18_1" id="element_18_1"> . <label for="element_18_1">Dollars</label> </span> 

As stated here , I suggest to filter out the text node(s), and remove them:

$('span')
  .contents()
  .filter(function() {
    return this.nodeType == 3; //Node.TEXT_NODE
  }).remove();

See fiddle .

这段代码有点粗糙,但应该可以

$("span:contains('.')").html($("span:contains('.')").html().replace('.',''));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM