如果特定的 html 元素包含特定值,如何向它们添加类
例如,我有以下 html:
<div id="stuff">
<span>1</span><span>2</span><span>3</span>
</div>
我需要以这种方式选择一些:
$('#stuff').find('<span>1</span><span>2</span>').addClass('2');
这应该将 html 变成这样:
<div id="stuff">
<span class="2">1</span><span class="2">2</span><span>3</span>
</div>
但是,上面的方法不起作用。有人知道如何使用 jQuery 通过查找 html 直接从 DOM 中选择内容吗?
另外,跨度必须按顺序选择,所以如果我有这个:
<div id="stuff">
<span>2</span><span>3</span><span>1</span>
</div>
并使用上面的JS,它不会做任何事情。
For example, I have the below html:
<div id="stuff">
<span>1</span><span>2</span><span>3</span>
</div>
And I need to select some in this fashion:
$('#stuff').find('<span>1</span><span>2</span>').addClass('2');
Which should turn the html into this:
<div id="stuff">
<span class="2">1</span><span class="2">2</span><span>3</span>
</div>
However, the above does not work. Anyone know how to use jQuery to select things directly off the DOM by looking for the html?
Also, the span's must be selected in order, so if I had this:
<div id="stuff">
<span>2</span><span>3</span><span>1</span>
</div>
And used the above JS, it would not do anything.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 $( '#stuff span:not(:contains(3))' ).addClass( '2' )
Use
$( '#stuff span:not(:contains(3))' ).addClass( '2' )
对了,如果你想查找各种内容,请执行以下操作:
输出:
right, if you want to look for various contents, do this:
The output:
您可以使用
:contains
伪类:http://jsfiddle.net/SJxTu/< /a>
You can use the
:contains
pseudo-class:http://jsfiddle.net/SJxTu/
我不完全清楚你的选择条件是什么,但你可以使用 jquery 过滤方法和函数来选择范围。
例如,来自文档:
http://api.jquery.com/filter/
您需要检查 $(this).text() === 是否任意
I'm not totally clear on what your selection condition is, but you Could use the jquery filter method with a function to select the spans.
For example from the docs:
http://api.jquery.com/filter/
You would need to check if $(this).text() === whatever