JS best way to check if block of elements contains one or few words than run code

Viewed 106

I want to check if a block of elements contains one or a few words and run specific code.

Within one theme I need to insert some links.

This is HTML:

<div>
<span class="nr">1</span>
<span class="block_subt">Element subtitle number one</span>
<a class="link" href="">Click here</a>
</div>
<div>
<span class="nr">2</span>
<span class="block_subt">Element subtitle number two</span>
<a class="link" href="">Click here</a>
</div>
<div>
<span class="nr">3</span>
<span class="block_subt">Element subtitle number three</span>
<a class="link" href="">Click here</a>
</div>

</div>

I want to create if statement that will check if the span with "block_subt" contains work like "three" it will append a link to anchor next to it. But also want to cover more blocks than one. This means cover another element if it contains the word "number three" add a different link to the next anchor. If another "block_subt" contains "two" append a different link.

What would be the best way to do it?

Obviously using one code multiple times would;t be a good idea. Plus code I'm running below will change every anchor and I want to change only one next to the HTML element that contains this specific word.

if ($(".block_subt:contains('Two')").length) {
        $(".link").attr("href", "http://www.google.com");
    }

Isn't a good idea. Could someone give me a pointer on this one?

1 Answers

If you did go the loop way, you could use .includes() and .next() to find the matching bits of text. Additionally, if you would like to search for more than just one word, you can use the .some() method.

var blocks = $('.block_subt');

blocks.each(function(i, div) {
  var text = $(div).text().replace("'", "").split(" ");
  var searchWords = ["number's", "one"];
  
  if (searchWords.some(word => text.includes(word))) {
    var a = $(this).next();
    $(a).attr("href", "http://www.google.com");
  };
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- WILL MATCH -->
<div>
  <span class="nr">1</span>
  <span class="block_subt">Element subtitle number's one</span>
  <a class="link" href="">Click here</a>
</div>
<div>
  <span class="nr">1</span>
  <span class="block_subt">Element subtitle number one</span>
  <a class="link" href="">Click here</a>
</div>

<!-- WILL NOT MATCH -->
<div>
  <span class="nr">2</span>
  <span class="block_subt">Element subtitle numbers two</span>
  <a class="link" href="">Click here</a>
</div>
<div>
  <span class="nr">3</span>
  <span class="block_subt">Element subtitle numbered three</span>
  <a class="link" href="">Click here</a>
</div>

It's a bit more verbose, but could maybe help get you in the right direction.

Related