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 :: how to get all scripts on a page javascript 
Javascript :: html js hide or show iframe 
Javascript :: material ui flex direction 
Javascript :: react counter animation 
Javascript :: calculate age given the birth date in the format yyyymmdd 
Javascript :: js if the reverse of a number is better than the original num 
Javascript :: appinsights trackException javascript 
Javascript :: chrome extension inject html 
Javascript :: javascript push 
Javascript :: how to hide api key in react app 
Javascript :: download pdf from drive js 
Javascript :: JQuery UI Saving Sortable List 
Javascript :: how to check alphabet case in javascript 
Javascript :: sequelize check if exists 
Javascript :: javascript this inside function 
Javascript :: Firebase: Error (auth/invalid-api-key). 
Javascript :: shopify guest login 
Javascript :: json returning object object 
Javascript :: js show element 
Javascript :: how to use react memo hooks 
Javascript :: file input only allow json 
Javascript :: Material-ui clock icon 
Javascript :: redux thunk 
Javascript :: react hook form with controlled input 
Javascript :: js array reduce error not a function 
Javascript :: full form of json 
Javascript :: leaflet flyto 
Javascript :: movement of objects in javascript 
Javascript :: reactjs facebook login popup trigger on load page 
Javascript :: can we use setstate inside build 
ADD CONTENT
Topic
Content
Source link
Name
9+2 =