Home > Blockchain >  How can I change the href of a anchor in javascript using query selector
How can I change the href of a anchor in javascript using query selector

Time:07-22

I cannot change an anchor's href when I do it returns saying that there was a null pointer

I tried using

fetch("https://jwapi.herokuapp.com/ck/results")
.then(res => res.json())
.then(data => {
    users = data.map(user => {
        const card = userCardTemplate.content.cloneNode(true).children[0]
        const header = card.querySelector("[data-header]")
        const description = card.querySelector("[data-description]")
        const link = card.querySelector("a[data-link]")
        header.textContent = user.name
        description.textContent = user.description
        link.href = user.link <-- ERROR HERE
        userCardContainer.append(card)
        return { name: user.name, description: user.description, element: card }
    })
    const value2 = searchInput.value
    if (value2 == "") {
        users.forEach(user => {
            user.element.classList.toggle("hide", true)
        })
    }
})

But it gave a error saying

Uncaught (in promise) TypeError: Cannot set properties of null (setting 'href')
at script.js:45:23
at Array.map (<anonymous>)
at script.js:38:22

if needed here is my html

<div  data-user-cards-container></div>
<template data-user-template>
    <a href="#" data-link>
        <div >
            <div  data-header></div>
            <div  data-description></div>
        </div>
    </a>
I tried console.log but and it returned null for card.herf but for user.link it returned the correct one

CodePudding user response:

The issue is that you are trying to find a link inside of card but card does not have a link inside of it. Actually the link contains a card which contains a header and a description.

What is the parent of the link element? Assume it is parent then this should work:

// I used `parent` to get the link, not `card`
const link = parent.querySelector("a[data-link]");

// now link should not be null.
// The reason you get an error is that you try to set href on a null object
link.href = 'http://www.google.com';

CodePudding user response:

You can try using document.querySelector("a").href = "{{url}}";

  • Related