Modify attributes of HTML elements dynamically created with JavaScript

1

On my website I make a request to the server PHP with AJAX , and I bring some links already created in PHP . All right up to here, but the problem is that I want to change these links to href with JavaScipt , but I do not change the URL of the links, this is my code:

var theLinks = document.querySelectorAll(".paginacion a");

  theLinks.forEach(function(element, index) {
    element.href = "http://es.stackoverflow.com";
  });

This problem only happens to the links brought by AJAX (they have the "pagination" class), since if I try to change the href of the links that are aesthetically on the page, those that were NOT brought by AJAX , if you change the href . For example, if I execute the following code instead of the previous one, I change the url of all the links, except those that have the class paginacion .

var theLinks = document.querySelectorAll("a");

      theLinks.forEach(function(element, index) {
        element.href = "http://es.stackoverflow.com";
      });

I hope and you can help me, I have several days giving back to the code and I can not find a solution, thanks.

    
asked by U.C 09.08.2018 в 00:37
source

2 answers

0

Your selector is incorrect. Try it like this:

var theLinks = document.querySelectorAll("a.paginacion");  

theLinks.forEach(function(element, index) {
    element.href = "http://es.stackoverflow.com";
  });
    
answered by 09.08.2018 в 00:40
0

The problem was that it did not consider the asynchronity of AJAX, and it executed the function of modifying the href even though the AJAX request that brought the links would not finish executing. What I did was just change to false the last parameter of the method open of XMLHttpRequest() :

  xhr.open("post", "admin/ajax/paginacion.php", false);

Thank you all for contributing something.

    
answered by 09.08.2018 в 17:58