Dummmy
Dummmy

Reputation: 798

Why does not DocumentFragment has getElementsByName?

I am following the instructions given on MDN to use <template>. Slightly different those give in example, my code is:

<template id="template">
    <tr>
        <td name="id"></td>
        <td name="name"></td>
        <td name="size"></td>
        <td name="Status">
        </td>
    </tr>
</template>
// ...
const item = document.importNode(template.content, true);
item.getElementsByName("id")[0].textContent = token;
item.getElementsByName("name")[0].textContent = file.name;
item.getElementsByName("size")[0].textContent = file.size;
fileList.appendChild(item);
// ...

However, it appears that item, of which the __proto__ is DocumentFragment has no getElementsByName method. Is it very confusing for me now that there is getElementById and querySelector.

Is there any reason why?

In case related, my browsers are FireFox Quantum 69.0.1 are Chrome Canary 79.0.3918.0.

Upvotes: 6

Views: 1187

Answers (2)

Manisha Sharma
Manisha Sharma

Reputation: 86

Document object is used to access and edit any HTML element getElementbyId(), getElementbyTagName() and getElementsByClassName() are method used by document object.

as you are trying to access Nodes of Template element using method of document object it will not work. you can implement the same code to append in your filelist object.

var Node1 = document.getElementById("template");
var Node2 = document.importNode(Node1, true);
document.getElementById("Table1").appendChild(Node2);
<template id="template">
    <tr>
       <td name="id"></td>
        <td name="name"></td>
        <td name="size"></td>
        <td name="Status">
        </td>
    </tr>
</template>

<Table id="Table1">
    <tr>
        <td name="id"> 1</td>
        <td name="name"> A </td>
        <td name="size"> 20 </td>
        <td name="Status"> N
        </td>
    </tr>
</Table>

Upvotes: 0

Barmar
Barmar

Reputation: 780974

DocumentFragment doesn't implement any of the getElementsBy* methods. However, it does implement querySelector(), so you can use

item.querySelector("[name=name]").textContent = token;

Upvotes: 5

Related Questions