Skip to content Skip to sidebar Skip to footer

Using Javascript To Select Div Leads To Page Not Found Error

I managed to get help on another thread for changing the title and link of an element using JavaScript (Issue with changing the title of a link using jQuery). I have tried implemen

Solution 1:

Here's a snippet that does what you want. Notice that you can use either a class (for multiple elements) or an id (for a singular element).

Basically, I used several commands to do what you wanted:

  • each() - should do the following function for each element found by the selector. this will refer to the DOM element
  • text() - return the text (without html) for that item
  • replaceWith() - will replace the element with whatever you want

in this example, every item with the class should-become-link will become a link after 2 seconds (because of the setTimeout). The original text inside the element will be used as the new href value.

$(document).ready(function() {
  setTimeout(function() {
    var element = $('.should-become-link');
    element.each(function(index) {
      var $this = $(this);
      var currentText = $this.text();

      $this.replaceWith(
        `<a href="${currentText}" target="_blank">Click Here</a>`
      );
    });
  }, 2000);

});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="buttons medium button-outlined should-become-link">
  https://www.hotmail.com
</div><div><ahref="http://www.google.com"target="_blank">shouldn't change!</a></div><div><ahref="//www.google.com"target="_blank">shouldn't change!</a></div><div><ahref="//www.google.com"target="_blank">shouldn't change!</a></div><div><ahref="//www.google.com"target="_blank">shouldn't change!</a></div><div><ahref="//www.google.com"target="_blank">shouldn't change!</a></div><divclass="buttons medium button-outlined should-become-link">
  https://www.google.com
</div>

and here's a codepen

Solution 2:

Use :eq() Selector to select the 4th li and then replace its content:

HTML:

 <div id="buttons medium button-outlined">https://www.hotmail.com</div>

JQuery:

var href2 = $('.container li:eq(3) > .buttons').html();
var link2 = "<a href='"+href2+"' target='_blank'>Click Here</a>";
$('.container li:eq(3) > .buttons').replaceWith(link2);

Working Demo here

Post a Comment for "Using Javascript To Select Div Leads To Page Not Found Error"