英文:
jquery append to element that contains specific text
问题
You can use the following jQuery code to insert HTML into the card-body
that contains the text "card b" in the card-header
:
$(document).ready(function() {
// Find the card with the desired card-header text
var cardB = $(".card-header:contains('card b')").closest(".card");
// Insert your HTML content into the card-body of card b
cardB.find(".card-body").html("Your HTML content goes here");
});
请注意,你需要将"Your HTML content goes here"替换为你要插入的实际HTML内容。
英文:
I have the following html which is a Bootstrap card with two nested cards.
<div id="myCard" class="card-body">
<div class="card">
<div class="card-header">
card a
</div>
<div class="card-body">
</div>
</div>
<div class="card">
<div class="card-header">
card b
</div>
<div class="card-body">
</div>
</div>
</div>
How can I insert html into the card-body
that contains the text "card b" in the card-header
using JQuery?
答案1
得分: 2
松散的遍历(如果元素被包装,更稳定):
$('.card-header:contains(card b)')
.parents('.card')
.find('.card-body')
.text('插入的文本');
更严格的遍历:
$('.card-header:contains(card b)')
.parent()
.children('.card-body')
.text('插入的文本');
请注意,这只是代码的一部分,如有其他需要,请告诉我。
英文:
Loose traversing (more stable if the elements get wrapped):
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$('.card-header:contains(card b)')
.parents('.card')
.find('.card-body')
.text('INSERTED TEXT');
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myCard" class="card-body">
<div class="card">
<div class="card-header">
card a
</div>
<div class="card-body">
</div>
</div>
<div class="card">
<div class="card-header">
card b
</div>
<div class="card-body">
</div>
</div>
</div>
<!-- end snippet -->
More strict traversing:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$('.card-header:contains(card b)')
.parent()
.children('.card-body')
.text('INSERTED TEXT');
<!-- language: lang-html -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="myCard" class="card-body">
<div class="card">
<div class="card-header">
card a
</div>
<div class="card-body">
</div>
</div>
<div class="card">
<div class="card-header">
card b
</div>
<div class="card-body">
</div>
</div>
</div>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论