'Refactor method chaining javascript
I call a function with bunch of nested method, i'm using web scraping tools called cheerio and i want to get the text out of it so i need to call a bunch of function. here's my example code.
var text = $(el)
.children()
.first()
.children()
.first()
.children()
.first()
.text()
.replace(/\s\s+/g, " ");
My question is, how can i simplify my function so I have the same result without chaining my function?
Solution 1:[1]
You can use nth-child(1) selector for the select first child.
You can use like that
$("div div:nth-child(1) div:nth-child(1) ul:nth-child(1)").text()
Solution 2:[2]
Use a loop
let child = $(el).children().first()
if (child) {
while (child.children().first()) {
child = child.children().first()
}
child.text().replace(/\s\s+/g, " ");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Engin Yüksel |
| Solution 2 | Steven Spungin |
