Todo el elemento es como a continuación:
<h2 class="font120 mt0 mb10 mobfont110 lineheight20 moblineheight15"><a href="https://demosite.com">demo text</a></h2>He ejecutado este siguiente comando:
const y = document.getElementsByClassName("font120 mt0 mb10 mobfont110 lineheight20 moblineheight15")[0].innerHTML; console.log(y);Y obtuve el siguiente resultado.
<a href="https://demosite.com">demo text</a>Ahora quiero obtener el enlace URL de href y luego hacer clic en él. ¿Cómo puedo hacerlo usando JavaScript? Además de eso, quiero agregar la declaración if else después de esto, que verificará si la URL de href cambia cada 5 minutos, si cambia, entonces debe hacer clic en el enlace de la URL de href; de lo contrario, solo debe actualizar la página.
Creo que esto se acerca a lo que quieres. Lo he probado localmente y funciona.
Hay una serie de anclas en el interior de los contenedores. Cada ancla tiene un evento de clic adjunto.
El valor href inicial se establece en el atributo href del primer ancla.
Luego, el código busca nuevos clics en los anclajes. Si hay uno, se inicia un temporizador. Si el nuevo href es el mismo que el guardado, después de cinco segundos, la página se vuelve a cargar. Si no es lo mismo, se carga la nueva página.
En cada nuevo clic, el temporizador se reinicia.
// Pick up the anchors with `querySelectorAll` const anchors = document.querySelectorAll('.demo a'); // Assign a handler to them for when the click // event is triggered. (Note `handleClick` returns // a new function that is actually assigned to the // listener because I wanted to use prevent any unnecessary // global variables, and you can do that with closure anchors.forEach(anchor => { anchor.addEventListener('click', handleClick()); }); function handleClick() { // Initialise the current href, and // the timer let current = anchors[0].href; let timer; // Return the function the listener will // be using return function (e) { // Stop the anchor from doing anything e.preventDefault(); // Get the new href from the clicked element const { href } = e.target; // Clear any timers clearTimeout(timer); // And set a new timer. If the current // href doesn't match the one on the clicked // element assign the page to a new location, // otherwise reload the current page. // This time is set for five seconds for testing // but you change that to five minutes (60000 x 5) timer = setTimeout(() => { if (current !== href) { // location.assign(href); console.log(`Redirecting to ${href}`); } else { // location.reload(); console.log(`Refreshing ${current}`); } current = href; }, 5000); } } <div class="demo"> <a href="https://demosite1.com">demo text 1</a> </div> <div class="demo"> <a href="https://demosite2.com">demo text 2</a> </div> <div class="demo"> <a href="https://demosite3.com">demo text 3</a> </div>Documentación adicional
Todo lo que necesita hacer es buscar el elemento a usando el selector CSS h2 a y luego obtener su atributo href :
console.log(document.querySelector("h2 a").href) <h2 class="font120 mt0 mb10 mobfont110 lineheight20 moblineheight15"><a href="https://demosite.com">demo text</a></h2>Para configurar una recarga de la página, puede configurar un
setTimeout("location.reload()",5*60*1000) Esto volverá a cargar la página actual después de cinco minutos y continuará haciéndolo, ya que la página recargada contendrá la misma función setTimeout (no activada).
Para verificar si el valor href ha cambiado de una a la siguiente versión recargada, deberá almacenar el valor en el almacenamiento localstorage y compararlo cada vez que se cargue la página con el valor href actual.