Home > Net >  Unable to get HTML element inside javascript file
Unable to get HTML element inside javascript file

Time:12-06

I have created a few html elements (span) inside javascript with the help of document.createElement, but I'm not able to add an event listener. When I try to retrieve those elements through document.getElementByName("span"), it returns an empty node list. I guess the elements are not available when loaded initially since I create those later. How can I retrieve those and add an event listener?

script.js

const items = ["Candles", "Decorations", "Chocolate"]
const checklist = document.getElementById("checklist")
const input = document.getElementById("newele");

function newElement(value){
    let div = document.createElement("div");
    let p = document.createElement("p");
    let span = document.createElement("span");
    
    p.innerText = value;
    
    let i = document.createElement("i");
    i.classList.add("fas", "fa-times");
    span.appendChild(i);
    
    div.classList.add("checklist-item");
    div.appendChild(p);
    div.appendChild(span);
    
    return div;
}

items.forEach((item) => {
    let p = newElement(item);
    checklist.appendChild(p);
});

let icon = document.getElementsByName("span");
console.log(icon);

index.js

<html>
    <head>
        <link rel="stylesheet" href="index.css">
        <link
      rel="stylesheet"
      href="https://use.fontawesome.com/releases/v5.13.0/css/all.css"
      integrity="sha384-Bfad6CLCknfcloXFOyFnlgtENryhrpZCe29RTifKEixXQZ38WheV i/6YWSzkz3V"
      crossorigin="anonymous"
    />
    </head>
    <body>
        <h1>Christmas Shopping List</h1>
        <div>
            <label for="newele">Add new item</label>
            <input type="text" id="newele"></input>
        </div>
        <div class="checklist" id="checklist"></div>

        <script src="index.pack.js"></script>
    </body>
</html>

CodePudding user response:

The problem is because of the selector method that you have been used. You should use getElementsByTagName("span"); rather than document.getElementsByName("span");

CodePudding user response:

as has already been correctly pointed out, a small error. But it might be more interesting to use a different selector function. If you select via the tag name, you get a collection. That means you still have to work with a key to address the right element. if you only have one span element then it would be [0]. But then my favourite method would be querySelector. Take a look in this small example:

const span1 = document.getElementsByTagName('span');    
console.log(span1[0]);
const span2 = document.querySelector('span');
console.log(span2)
<span>hello</span>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related