[英]wrap a div around text
我想在文本hello world
周围包装<input type="text">
。 Span
不应被其包围。
<div class="outer">
"hello world"
<span class="inner">Inner</span>
</div>
$('.inner').parent().contents().wrap('<input type="text"/>')
这将输入围绕文本和跨度包装。 我想避免跨度。 谁能帮帮我吗。 小提琴
您不能在某些内容周围包裹文本字段,而需要
var el = $('.inner')[0].previousSibling; $('<input />').val(el.nodeValue.trim()).insertBefore('.inner'); $(el).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="outer"> "hello world" <span class="inner">Inner</span> </div>
您可以将内部div保存在变量中,然后在替换外部div中的内容之后将其附加在末尾。 像这样:
// Save the inner tag
var inner = document.querySelector(".inner").outerHTML;
// Remove the inner tag
document.querySelector(".inner").parentNode.remove(document.querySelector(".inner"));
// Wrap the text, then add the saved tag.
document.querySelector(".outer").innerHTML("<input type=\"text\">"
+ document.querySelector(".outer").innerHTML
+ "</input>" + inner);
尝试利用.filter()
.replaceWith()
// return `#text` node having `"hello world"` as `textContent` var text = $(".inner").parent().contents().filter(function() { return this.nodeType === 3 && /hello world/.test(this.textContent) }); // replace `text` with `input type="text"` element // having value of `text` `textContent` text.replaceWith(function() { return "<input type=text value=" + this.textContent + "/>" })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div class="outer"> "hello world" <span class="inner">Inner</span> </div>
只需从内容中获取第一个元素:
$('.inner').parent().contents().first().wrap("<input type='text'/>");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="outer"> "hello world" <span class="inner">Inner</span> </div>
结果是:
<div class="outer">
<input type="text">hello world</input>
<span class="inner">Inner</span>
</div>
请注意,我提供这些信息只是为了帮助您了解contents()
方法的工作方式。
<input type="text">hello world</input>
不是有效的HTML 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.