Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to create an anchor tag in javascript

//for adding a link through JavaScript 
let anchor=document.createElement("a");
anchor.href="_anylinkthatyouwanttoadd_";
anchor.innerText="Go to the above link";//optional
console.log(anchor)
let to_add=document.getElementById("the-id-of-the-element-where-you-want-to-add")
to_add.appendChild(anchor)
Comment

javascript create anchor link

const createAnchorLink = (id) => {
  const anchor = document.createElement("a");
  anchor.className = "anchor-link";
  anchor.href = "#" + id;
  return anchor;
};

window.onload = () => {
  let increment = 0;
  [...document.querySelectorAll("h1, h2, h3, #spec > ol > li > p")].forEach(
    (el) => {
      if (el.id) {
        const anchorLink = createAnchorLink(el.id);
        el.insertBefore(anchorLink, el.firstChild);
      } else {
        increment++;
        el.parentElement.id = "spec-item-" + increment;
        const anchorLink = createAnchorLink(el.parentElement.id);
        el.parentElement.insertBefore(anchorLink, el);
      }
    }
  );

  const hash = window.location.hash;
  if (hash) {
    const targetElTop = document.querySelector(hash).offsetTop;
    window.scrollTo(0, targetElTop);
  }
};
Comment

PREVIOUS NEXT
Code Example
Javascript :: javascript parse and validate json 
Javascript :: unrecognized json property java 
Javascript :: how to change the query parameter of the url in javascript 
Javascript :: disable back button in react native 
Javascript :: moment date difference in days 
Javascript :: jquery sum all input values 
Javascript :: loop through json object javascript 
Javascript :: Firebase CLI v11.0.1 is incompatible with Node.js v14.17.6 Please upgrade Node.js to version = 14.18.0 
Javascript :: turn nodelist into array 
Javascript :: update tooltip jquery 
Javascript :: react native get route name 
Javascript :: invalid chai property 
Javascript :: type float loopback model 
Javascript :: bright red in javascript 
Javascript :: jquery all elements whose id contains 
Javascript :: install aos in react 
Javascript :: csrf token ajax header 
Javascript :: map function react not appearing 
Javascript :: js arrotondare numeri 
Javascript :: @angular/common 
Javascript :: pdf dark 
Javascript :: how to square a value in javascript 
Javascript :: video js toggle play pause 
Javascript :: give the player an item skript 
Javascript :: node http post 
Javascript :: status nodejs 
Javascript :: iframe in angular 
Javascript :: nazmul hassan 
Javascript :: react native text truncate 
Javascript :: combine two arrays javascript 
ADD CONTENT
Topic
Content
Source link
Name
6+1 =