2015-10-01 100 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>