[英]Replacing a label's text if there's a nested input element
更改标签的文字似乎很简单 :
var /**HTMLLabelElement*/ label = ...;
label.innerHTML = "...";
或者,使用jQuery :
var /**HTMLLabelElement*/ label = ...;
$(label).text("...");
如果标签包装<input/>
元素,则上述任何一种都无法正常工作:
<label><input type="checkbox">Text</label>
- 在这种情况下, <input/>
元素将与旧文本一起替换。
如何更改标签的文本,而不影响其子元素?
过滤掉非空文本子节点并将其替换为新内容。
$('label') // get all child nodes including text and comment .contents() // iterate and filter out elements .filter(function() { // check node is text and non-empty return this.nodeType === 3 && this.textContent.trim().length; // replace it with new text }).replaceWith('new text');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <input type="checkbox">Text</label>
纯JavaScript方法
var label = document.querySelector('label'); // get all child nodes and update the text node from it label.childNodes[2].textContent = 'new text' // If you don't know the position // then iterate over them and update // based on the node type
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <input type="checkbox">Text</label>
使用javascript nextSibling
属性选择输入的兄弟文本。
document.querySelector('input').nextSibling.nodeValue = "newText";
<label> <input type="checkbox"> Text </label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.