在jQuery中select一个包装元素
我正在jquery和nodejs在一个漂亮的旧网站做一些过滤,我想select由p
包裹的b
元素。 我的意思只是那些没有文字的p
包装。
我想要匹配的
<p><b>Some text</b></p>
我不想匹配的
<p>Some other text and some other elements <a>link</a><b>Some text</b> and some more text of the parent p </p>
你知道我可以select这第一个包裹的元素,而不是第二个? 有没有select器来select这个?
您可以使用filter
方法:
$('p > b').filter(function() { return $(this.parentNode) // get the p element .contents() // get all the child nodes .not(this) // exclude the current `b` element .length === 0; });
尝试使用:first-child
select器
alert($(">b:first-child", "p").text())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <p><b>Some text</b></p> What I don't want to match <p>Some other text and some other elements <a>link</a><b>Some text</b> and some more text of the parent p </p>
不确定。 你看起来像这样吗?
HTML
<p>Some other text and some other elements <a>link</a><b>Some text</b> and some more text of the parent p</p> <p><b>Some text</b></p> <p>Some other text and some other elements <a>link</a><b>Some text</b>
和一些更多的父母文本
CSS
pb:first-child:nth-of-type(1) { font-size:30px; }
DEMO
使用substring()
检查html()
的前3个字母是否等于<b>
。
$("p").each(function() { if ($(this).html().substring(0, 3) == "<b>") { // Do whatever } });
如这个JSFiddle Demo所示。
- 如何使用下载的纱线依赖关系
- Node / Grunt – Autoprefixer – 如何添加configuration到我的Gruntfile.js&如何检查支持的浏览器?
- Node.js公共css文件404找不到
- 为什么翡翠文件不想加载CSS
- IE9,歌剧和旧的Safari试图下载我的Node.js服务器托pipe的网站作为一个文件?
- CSS文件和Javascript文件不加载在我的HTML文件的根文件夹 – Openshift
- 离子 – 不能开始吞咽
- jQuery底部固定div切换向上移动所有div
- Webpack,sass-loader(或css-loader)在node_modules里嵌套文件导入。 文件未find