I'm doing some filtering in a pretty old web with jquery and nodejs, and I want to select the b
elements that are wrapped by a p
. I mean only those that are wrapped with a p
without text.
What I want to match
<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>
Do you know any way I can select this first wrapped element and not the second? Is there any selector to select this?
You can use the filter
method:
$('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;
});
Try using :first-child
selector
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>
Not sure. Are you looking like this?
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>
and some more text of the parent p
CSS
p b:first-child:nth-of-type(1)
{
font-size:30px;
}
Use substring()
to check if the first 3 letters of html()
are equal to <b>
.
$("p").each(function() {
if ($(this).html().substring(0, 3) == "<b>") {
// Do whatever
}
});
As shown in this JSFiddle Demo .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.