[英]Replace text from span if div text contains specific text
Replace from <span class="redbadge">
the text No with Yes if div contains the text I am now visible
.如果div 包含
I am now visible
的文本,则从<span class="redbadge">
将文本No替换为 Yes 。
HTML HTML
<div class="visibleonsearch">
<span class="redbadge">No</span>
I am now visible.
</div>
jQuery jQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function () {
$(".visibleonsearch").text(function () {
return $(this).text().replace("No", "Yes");
});
</script>
I am not familiar with jQuery to add the condition if .我不熟悉 jQuery 添加条件if 。
You can try using :contains
selector like the following way:您可以尝试使用
:contains
选择器,如下所示:
jQuery(document).ready(function () { if($(".visibleonsearch:contains(I am now visible)").length){ var span = $('.visibleonsearch').find('.redbadge'); span.text(span.text().replace("No", "Yes")); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="visibleonsearch"> <span class="redbadge">No</span> I am now visible. </div>
If the goal is to change the text of the span
while leaving the span
itself in the DOM then you can use :contains
to find the relevant .redbadge
element, like this:如果目标是更改
span
的文本,同时将span
本身留在 DOM 中,那么您可以使用:contains
查找相关的.redbadge
元素,如下所示:
$('.visibleonsearch:contains("I am now visible").redbadge').text('Yes');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="visibleonsearch"> <span class="redbadge">No</span> I am now visible. </div>
try this code
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".visibleonsearch:contains(I am now visible.)").find(".redbadge").text(function () {
return $(this).text().replace("No", "Yes");
});
});
</script>
</head>
<body>
<div class="visibleonsearch">
<span class="redbadge">No</span>
I am now visible.
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.