2015-10-01 61 views
1

我想圍繞文字hello world圍繞<input type="text">Span不應該被它包圍。圍繞文字環繞一個div

<div class="outer"> 
    "hello world" 
    <span class="inner">Inner</span> 
</div> 

$('.inner').parent().contents().wrap('<input type="text"/>') 

這一個圍繞文本和跨度包裝輸入。我想避免跨度。誰能幫幫我嗎。 fiddle

+0

''不允許有孩子。這將導致HTML無效。 – torvin

+0

試試這個http://jsfiddle.net/4osn1uqp/1/ –

回答

1

不能環繞某些內容的文本字段,你需要

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>

-1

從內容只取第一個元素:

$('.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

0

您可以將內部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); 
0

嘗試利用.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>