Utilizing template literals enforces a .toString()
call on the element
reference, resulting in [object HTMLLIElement]
.
As stated in the documentation:
If toString() is not customized in an object, it returns ""[object type]"", where type represents the object type.
Omitting the template literal leaves the rendering of the value to the browser, which yields the raw HTML of the element by implicitly invoking element.valueOf()
.
const div = document.querySelector("div");
console.log(div); // Implicit .valueOf() call
console.log(div.valueOf()); // Explicit .valueOf() call
const el = div;
console.log(`${div}`); // Implicit .toString() call
console.log(div.toString()); // Explicit .toString() call
<div>test</div>
Therefore, when using template literals, bear in mind that you are requesting to output the string representation of the element itself rather than a specific property of the element.
In your scenario, template literals are unnecessary since the forEach
arguments provide access to the required data via the element node interface, and calling element.outerHTML
will yield the complete HTML of the element.
document.querySelectorAll("#start .sel").forEach(
(element, pos) => {
// The forEach element argument provides a reference to the
// element instance being iterated. You can access anything
// you need through that element's API:
console.log(element.nodeName,
element.className,
element.textContent,
element.outerHTML,
pos);
}
);
<div id="start">
<ul>
<li class="sel">valoare 1</li>
<li class="sel">valoare 2</li>
<li class="sel">valoare 3</li>
<li>valoare 4</li>
<li class="sel">valoare 5</li>
</ul>
</div>