[英]How do I wrap all text nodes with <p> in a div that also may contain other <p> tags and tags such as <strong> using jQuery?
[英]jQuery - wrap all unwrapped text in p tags
我有一种情况,以下代码被写入我的页面。
<div>
Some text here which is not wrapped in tags
<p>Some more text which is fine</p>
<p>Blah blah another good line</p>
</div>
在这种情况下,它似乎总是第一行没有包装在p标签中,这可能使解决方案变得更容易,尽管并非每次都如此。 有时候很好。
我需要做的是确定第一行是否被包裹,如果没有,则将其包裹起来。
不幸的是我不知道从哪里开始这个问题所以任何帮助将不胜感激。
尝试使用此代码来包装未包含<p>
标记的任何TextNode。
function getTextNodesIn(node, includeWhitespaceNodes) {
var textNodes = [], whitespace = /^\s*$/;
function getTextNodes(node) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) {
textNodes.push(node);
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNodes(node.childNodes[i]);
}
}
}
getTextNodes(node);
return textNodes;
}
var textnodes = getTextNodesIn($("#demo")[0]);
for(var i=0; i < textnodes.length; i++){
if($(textnodes[i]).parent().is("#demo")){
$(textnodes[i]).wrap("<p>");
}
}
这是一个jsfiddle ,显示了这一点。
PS:TextNode检测部分已经从这个答案借来
你去吧: http : //jsfiddle.net/RNt6A/
$('div').wrapInner('<p></p>');
$('div p > p').detach().insertAfter('div p');
试试这个 :-
<div class="container">
Some text here which is not wrapped in tags
<p>Some more text which is fine</p>
<p>Blah blah another good line</p>
</div>
JS
$(function(){
var $temp = $('<div>');
$('div.container p').each(function(){
$(this).appendTo($temp);
});
if($.trim( $('div.container').html() ).length){
var $pTag = $('<p>').html($('.container').html());
$('div.container').html($pTag);
}
$('div.container').append($temp.html());
});
以下是工作示例: -
jQuery 处理文本节点很糟糕 ,所以你需要对它进行一些直接的DOM操作。 这也使用“修剪”功能。 。 它在jsfiddle 。
var d = $("div")[0];
for(var i=0; i<d.childNodes.length; i++) {
if(d.childNodes[i].nodeType === 3 &&
d.childNodes[i].textContent.replace(/^\s+|\s+$/g, "")) {
wrapNode(d.childNodes[i]);
}
}
function wrapNode(node) {
$(node).replaceWith("<h1>" + node.textContent + "</h1>");
}
遇到类似的需求并尝试使用解决方案@Arash_Milani。 解决方案有效,但是当页面也需要进行ajax调用时,我遇到了冲突。
经过一番挖掘后,我使用.contents()
方法在api.jquery.com上找到了一个相当简单的解决方案:
$('.wrapper').contents().filter(function() { return this.nodeType === 3; }).wrap('<p class="fixed"></p>').end();
p.good { color: #09f; } p.fixed { color: #ff0000; text-align: center; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="wrapper"> Some plain text not wrapped in any html element. <p class="good">This text is properly wrapped in a paragraph element.</p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.