I want to wrap a <input type="text">
just around text hello world
. Span
should not be surrounded by it.
<div class="outer">
"hello world"
<span class="inner">Inner</span>
</div>
$('.inner').parent().contents().wrap('<input type="text"/>')
This one wraps input around both text and span. I want to avoid around span. Can anyone please help me. fiddle
You can't wrap a text field around some content, you need
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>
You could save the inner div in a variable, and then appending it at the end after you replace what is in the outer div. Like this:
// 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);
Try utilizing .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>
Just take the first element from the contents:
$('.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>
Result is:
<div class="outer">
<input type="text">hello world</input>
<span class="inner">Inner</span>
</div>
Note that I have provided that only to help you understand how contents()
method works.
<input type="text">hello world</input>
is not a valid HTML .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.