Home > other >  jQuery: If h1 has specific text then link should be added
jQuery: If h1 has specific text then link should be added

Time:11-12

This is my try so far:

$("h1").each(function() {
  if ($(this).text() == "Google") {
    $(this).click(function() {
      window.open("https://google.com/");
    });
  }
});

$("h1").each(function() {
  if ($(this).text() == "Facebook") {
    $(this).click(function() {
      window.open("https://facebook.com/");
    });
  }
});

$("h1").each(function() {
  if ($(this).text() == "Instagram") {
    $(this).click(function() {
      window.open("https://instagram.com/");
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Google</h1>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If the text of the h1 is for Example Google, then the website link for the Google website should be added. If the text is Facebook, then the website link for the Facebook website should be added. It should update automatically if the h1 changes.

My try does not work unfortunately, and it looks very laborious.

Has someone an idea how to do that in a smart way?

Thanksss <3

CodePudding user response:

It looks like window.ooen() does not work in the SO snippet. That is why I have added the console.log() here for demo purposes.

$("body").on("click","h1",function() {
  const url=$(this).text().toLowerCase();
  if(["google","facebook","instagram"].indexOf(url)>-1){
   console.log(`opening ${url}`); 
   window.open(`https://${url}.com/`);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Google</h1>
<h2>Google</h2> 
<h1>Instagram</h1>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related