I need to get all the HTML divs that contains many HTML elements which has the innerText = ‘ * ‘ and store it in an array, How can I achieve that using typescript?. If I find a span containing the innerText= ‘ * ‘, I need to put the div inside an array. Here, in my code, there are 2 divs contains span elements with innerText= ‘ * ‘ and I need to put only that 2 divs inside an array. I don’t need the 3rd div in the array, because it does not contains any HTML elements with innerText=”*”.
<div class="div"> <label> <span> Subject </span> <span> * </span> </label> </div> <br> <div class="div"> <label> Yes/No </label> <span> * </span> </div> <br> <div class="div"> <label> Email Id </label> <span> hello </span> </div>
Advertisement
Answer
There is currently no standard API to get elements by their content, so you would have to loop over them manually:
const myElements = Array.from(document.querySelectorAll('*')) .filter(() => this.children.length === 0 && this.textContent === ' * ');
The ‘*’ passed here to querySelectorAll
is not related to the text you are looking for, it’s just the universal selector to select all elements on the page. As this might be expensive, you’d better use some other selector to limit the scope.