[英]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.