Match partial text in a div and if it matches text in another div then show a span - jquery and javascript

淺唱寂寞╮ 提交于 2020-05-17 05:50:54

问题


I need to show the quantity in stock of a product if there is an out of stock message for it:

<div class="OutOfStockMessage">Sorry, Avocado is not available in the quantity that you selected. Please select a lower quantity to be able to place this order.</div>
<div class="ItemDecription">Avocado<span class="Quantity" style="display:none"> 16 pieces in stock</span></div>
<div class="ItemDecription">Tomato<span class="Quantity" style="display:none"> 97 pieces in stock</span></div>
<div class="ItemDecription">Mushroom<span class="Quantity" style="display:none"> 217 pieces in stock</span></div>

I tried this jQuery however it only works with an exact text match and not with a partial text match:

if ( $(".OutOfStockMessage").text() == $(".ItemDecription").text() ) {
$(".Quantity").show();
}

Here is the Fiddle: https://jsfiddle.net/8jmpnwuy/

When .OutOfStockMessage contains the word 'Avocado' plus other words then I need the span inside of the div which contains the word 'Avocado' to show.


回答1:


You can use .filter() function to find all itemdescription divs with partial text matching OutOfStockMessage message text.

You can then find the immediate span elements in these sets and show them. I would suggest using a class selector instead of immediate child selector. This makes it less error prone to DOM changes

var stockMessageTxt= $(".OutOfStockMessage").text();
var $itemDescrptnToShow = $(".ItemDecription").filter(function(){
  return stockMessageTxt.includes($(this).clone()
    .children() //select all the children
    .remove()   //remove all the children
    .end()  //again go back to selected element
   .text());
});
$('.Quantity', $itemDescrptnToShow).show();

Working Demo



来源:https://stackoverflow.com/questions/61723412/match-partial-text-in-a-div-and-if-it-matches-text-in-another-div-then-show-a-sp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!