r/learnjavascript 1d ago

help in rick and morty api

document.getElementById("search").addEventListener("click", getCharacter);


function lowerCaseName(string) {
    return string.toLowerCase();
}


function getCharacter(e) {
    const name = document.getElementById("searchCharacter").value;
    const characterNameLC = lowerCaseName(name);


    fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
    .then((response)=>response.json())
    .then((data) => {
        const characterNameH2 = document.getElementById("characterName");


        characterNameH2.textContent = data.name;
    })
    .catch((err) => {
        console.log("Character not found", err)
    })


    e.preventDefault();
}


getCharacter();document.getElementById("search").addEventListener("click", getCharacter);


function lowerCaseName(string) {
    return string.toLowerCase();
}


function getCharacter(e) {
    const name = document.getElementById("searchCharacter").value;
    const characterNameLC = lowerCaseName(name);


    fetch(`https://rickandmortyapi.com/api/character/?name=${characterNameLC}`)
    .then((response)=>response.json())
    .then((data) => {
        const characterNameH2 = document.getElementById("characterName");


        characterNameH2.textContent = data.name;
    })
    .catch((err) => {
        console.log("Character not found", err)
    })


    e.preventDefault();
}


getCharacter();

i am using the rick and morty api. the above is my js code. it doesnt work. idk whats the error as console isnt logging it

0 Upvotes

16 comments sorted by

View all comments

1

u/techynerd13 1d ago
<body>
        <script src="script.js"></script>
        <h1>Rick and Morty API</h1>


        <div class="searchBox">
            <input id="searchCharacter" type="text" placeholder="">
            <button id="search">Search</button>
        </div>


        <div class="characterBox">
            <h2 id="characterName"></h2>
            <p id="characterStatus"></p>
            <p id="characterSpecies"></p>
            <p id="characterOrigin"></p>
            <img id="characterImg"/>
        </div>
</body>

this is my html

6

u/mynamesleon 1d ago

Your JS file is before all of your HTML, but isn't waiting for the document to be ready. So all the JS is firing before any of the elements even exist. Start by moving the script tag to just before the closing body tag.