I'm trying to scrape a website which has a structure like this:
var elems = document.getElementsByClassName("breakfast");
elems = [...elems] // Converts HTMLCollection to Array
elems = elems.map(elem => elem.children[0])
elems = elems.filter(elem => elem !== undefined)
elems = elems.map(elem => elem.getAttribute("title"))
document.write(elems)
<div class="breakfast">
<p title="1">Bagels</p>
</div>
<div class="breakfast">
</div>
<div class="breakfast">
<p title="2">Bread</p>
</div>
<div class="breakfast">
<p title="3">Toast</p>
</div>
<div class="breakfast">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The above Javascript works just fine, but I want the undefined
values, instead of them not showing up, I want them to be 0.
My first thought was to use the ternary operator, I, however, do not know how to make a new HTML-element where elements such as the children or the attributes are accessible. I know of HTMLParagraphElement
, the documentation is sadly not enough for me to figure out how to do this.
CodePudding user response:
The optional chaining operator (
?.
) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.The
?.
operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.
and
The nullish coalescing operator (
??
) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
var elems = [...document.querySelectorAll(".breakfast")];
elems = elems.map(elem => elem.children[0])
// elems = elems.filter(elem => elem !== undefined)
elems = elems.map(elem => elem?.getAttribute("title") ?? 0)
document.write(elems)
<div class="breakfast">
<p title="1">Bagels</p>
</div>
<div class="breakfast">
</div>
<div class="breakfast">
<p title="2">Bread</p>
</div>
<div class="breakfast">
<p title="3">Toast</p>
</div>
<div class="breakfast">
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>