jquery 在未嵌套的文本周围添加标签
jquery add tag around unnested text
这是一个很难找到标题的问题,但就是这样。
我知道了 HTML,我无法更改
<ul>
<li>
First part of the list
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
</li>
<li>
Second part of the list
<ul>
<li>item 3</li>
</ul>
</li>
</ul>
我想将内容应用于 "first part of the list" 和 "Second part of the list" 部分, 但不是嵌套的 ul 部分 ,例如 CSS 转换 scaleY,以及自定义 Jquery onClick 方法。
所以,我想要的解决方案是使用 JQueryly 添加这些内容。
这可能吗?
非常感谢
为此,您可以 filter()
li
contents()
检索其中的文本节点,然后将其包装在 span
中并应用所需的 CSS 规则。像这样:
$('#container > ul > li').each(function() {
var foo = $(this).contents().filter(function() {
return this.nodeType == 3 && this.textContent
}).wrap('<span />');
});
#container > ul > li > span {
color: red;
display: inline-block;
transform: scaleY(2);
margin: 0 0 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<ul>
<li>
First part of the list
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
</li>
<li>
Second part of the list
<ul>
<li>item 3</li>
</ul>
</li>
</ul>
</div>
这是一个很难找到标题的问题,但就是这样。
我知道了 HTML,我无法更改
<ul>
<li>
First part of the list
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
</li>
<li>
Second part of the list
<ul>
<li>item 3</li>
</ul>
</li>
</ul>
我想将内容应用于 "first part of the list" 和 "Second part of the list" 部分, 但不是嵌套的 ul 部分 ,例如 CSS 转换 scaleY,以及自定义 Jquery onClick 方法。
所以,我想要的解决方案是使用 JQueryly 添加这些内容。
这可能吗?
非常感谢
为此,您可以 filter()
li
contents()
检索其中的文本节点,然后将其包装在 span
中并应用所需的 CSS 规则。像这样:
$('#container > ul > li').each(function() {
var foo = $(this).contents().filter(function() {
return this.nodeType == 3 && this.textContent
}).wrap('<span />');
});
#container > ul > li > span {
color: red;
display: inline-block;
transform: scaleY(2);
margin: 0 0 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<ul>
<li>
First part of the list
<ul>
<li>item 1</li>
<li>item 2</li>
</ul>
</li>
<li>
Second part of the list
<ul>
<li>item 3</li>
</ul>
</li>
</ul>
</div>