I want to check if the text exist and remove it. I need to find if the text exist and remove the parent items. For example If the the With Name + Date exist then remove :
<dt>Font</dt>
<dd>Arial </dd>
Another example if the With Name + Date + Time exist then remove:
<dt>Font</dt>
<dd>Comic Sans </dd>
My code:
jQuery( document ).ready(function() {
if (jQuery('.item-options dd:contains("With Name")').length > 0)
{
var parent = jQuery('.item-options dd:contains("With Name")').parent('dl');
jQuery(parent).find('dt:contains("Font")').html('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="item-options">
<dt>Radio test</dt>
<dd>With Name </dd>
<dt>Font</dt>
<dd>no font selected </dd>
</dl>
<dl class="item-options">
<dt>Radio test</dt>
<dd>With Name + Date</dd>
<dt>Font</dt>
<dd>Arial </dd>
</dl>
<dl class="item-options">
<dt>Radio test</dt>
<dd>With Name + Date + Time</dd>
<dt>Font</dt>
<dd>Comic Sans </dd>
</dl>
My issue is because With Name exist in all and my javascript is apply to all. How I can make the javascript to search exactly?
-
Possible duplicate of make jQuery's `:contains()` select only exact stringPhiter– Phiter2016年04月15日 17:14:43 +00:00Commented Apr 15, 2016 at 17:14
2 Answers 2
You can use jQuery's filter function. The contains selector will not try to get an exact match, but, like the name says, a string that contains the desired text.
jQuery( document ).ready(function() {
if (jQuery('.item-options dd').filter(function() {
return jQuery(this).text() === "With Name";
}).length > 0)
{
var parent = jQuery('.item-options dd:contains("With Name")').parent('dl');
jQuery(parent).find('dt:contains("Font")').html('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<dl class="item-options">
<dt>Radio test</dt>
<dd>With Name </dd>
<dt>Font</dt>
<dd>no font selected </dd>
</dl>
<dl class="item-options">
<dt>Radio test</dt>
<dd>With Name + Date</dd>
<dt>Font</dt>
<dd>Arial </dd>
</dl>
<dl class="item-options">
<dt>Radio test</dt>
<dd>With Name + Date + Time</dd>
<dt>Font</dt>
<dd>Comic Sans </dd>
</dl>
Looks ugly, but works.
5 Comments
if you know the html architecture or otherwise remove whatever you want.i hope this will help you.
$( document ).ready(function() {
if ($('.item-options dd:contains("With Name")').length > 0)
{
var parent = $('.item-options');
var children = $('.item-options').find("dd");
$(children).each(function(i,e){
if(~$(e).text().indexOf("With Name + Date + Time")){
$(e).nextAll().remove();
}
else if(~$(e).text().indexOf("With Name + Date")){
$(e).nextAll().remove();
}
});
}
});