Skip to content Skip to sidebar Skip to footer

Javascript Remove Null From The Result

For the sake of me i can't get the Filter (.filter(function(d,i){return d})) to eliminate 'undefined' or '0' working on this array. The script runs within a Applescript applet and

Solution 1:

First, you can get rid of some of that inner DOM selection by making your initial qSA selection more specific: ".product_card a .product_card__title".

Then you can use .filter() by returning the result of checking if each element .includes() the "rocker" text. Do this before mapping the .href.

Finally, .map() those results to the .href of each .parentNode, since we selected the child with the text directly.

var x = Array.prototype.slice.call(document.querySelectorAll(".product_card a .product_card__title"))
  .filter(function(d) {
    return d.textContent.toLowerCase().includes("rocker")
  })
  .map(function(d) { return d.parentNode.href });

document.getElementById("result").textContent = JSON.stringify(x);
<divclass="product_card powersearch__product_card"><ahref="/shop/XYZ"class="js-search-product-link"><divclass="product_card__image"style="background-image:url(https://image.jpg);"></div><divclass="product_card__title">some rocker</div><divclass="product_card__meta">€14</div></a></div><br><divclass="product_card powersearch__product_card"><ahref="/shop/ZXY"class="js-search-product-link"><divclass="product_card__image"style="background-image:url(https://image.jpg);"></div><divclass="product_card__title">returns undefined</div><divclass="product_card__meta">€14</div></a></div><br><divid="result">

And of course it's a bit cleaner with modern syntax.

const x = Array.from(document.querySelectorAll(".product_card a .product_card__title"))
  .filter(d => d.textContent.toLowerCase().includes("rocker"))
  .map(d => d.parentNode.href);

document.getElementById("result").textContent = JSON.stringify(x);

Post a Comment for "Javascript Remove Null From The Result"