我试图使用jQuery包装html文档中的intro / help文本。它不在任何标记内,而是在两个封闭的html标记之间。
例如,请参阅附带的代码段。第二个结束标签也可以不是 <p>
。
var txtHelp = jQuery('b.page-title').nextUntil('p').text();
console.log(txtHelp);
//jQuery('b.page-title').nextUntil('p').text().wrap("<p />");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
5016
2017-07-19 06:21
起源
$('b.page-title')[0].nextSibling.textContent - haim770
答案:
该 nextUntil()
方法不选择文本节点。
您可以通过获取文本节点 nextSibling
节点的属性和获取文本内容 textContent
文本节点的属性。
var txtHelp = jQuery('b.page-title')[0] // get the dom object
.nextSibling // get the text node next to it
.textContent; // get text content
console.log(txtHelp);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
更新1: 如果你想用a包装元素 p
然后标签就像。
$( // wrap by jquery to convert to jQuery object
$('b.page-title')[0] // get the dom element also you can use `get(0)`
.nextSibling // get the textnode which is next to it
).wrap('<p/>'); // wrap the element by p tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
更新2: 如果它包含 br
标签,你想把它作为文本包含然后做一些棘手的使用 contents()
方法。
var get = false;
$($('b.page-title')
.parent() // get it's parent
.contents() // get all children node including text node
.filter(function() {
if ($(this).is('b.page-title')) {
get = true; // if element is 'b.page-title' then set flag true , we need to get element from here
return false // return false that we don't need the 'b.page-title'
}
if ($(this).is('p')) // check element is `p`, that we need to get element uptop tag
get = false; // update flag
return get; // return the flag for filtering
})).wrapAll('<p/>'); // use wrapAll to wrap all elements withing single tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b class="page-title"><h4>System Log</h4><hr class="text-primary"></b>
How to select this text
<br/>and wrap it in new P-Tag
<p align="center">This can by any html tag</p>
8
2017-07-19 06:25
谢谢这完全有用..但是这里有[0]的重要性,我发现没有它就行不通。如果内容中有一些内容呢? How to select this text and wrap it in new P-Tag<br><br> new line<br> new line 我用了 jQuery('b.page-title').nextUntil(':not(br)').remove(); 这在上面的代码之前,但只包装第一行。 - Amit Shah
@AmitShah: 1) [0] 从jQuery对象获取dom对象 2) 更新答案请检查 - Pranav C Balan
对于纯jQuery方法,您可以尝试这样做:
var contents = $('b.page-title').contents(),
textNodes = contents.filter(function() { return this.nodeType === 3; });
console.log(textNodes[0].textContent);
看到 内容()
1
2017-07-19 06:29