0

I have a page which has multiple textarea's which are made with dynamic names and identical classes. This means I cannot select them by id, name, class or type.

What I do know is that out of the 5 textarea's, I need the first one and I want to change the value of that one.

Can anyone tell me how I can do this with chromedp? been trying for two days without any progress.

Found the answer:

const n = document.querySelector('.elementor-repeater-fields:nth-child(2) textarea'); console.log(n);

1 Answers1

0

Use pseudo-class :first-child or :nth-child to select the target element. For example:

package main

import (
    "context"
    "fmt"
    "net/http"
    "net/http/httptest"
    "time"

    "github.com/chromedp/chromedp"
)

func main() {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, `
<html>
  <body>
    <textarea></textarea>
    <textarea></textarea>
    <textarea></textarea>
  </body>
</html>
`)
    }))
    defer ts.Close()

    opts := append(chromedp.DefaultExecAllocatorOptions[:],
        chromedp.Flag("headless", false),
    )
    ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
    defer cancel()
    ctx, cancel = chromedp.NewContext(ctx)
    defer cancel()

    err := chromedp.Run(ctx,
        chromedp.Navigate(ts.URL),
        chromedp.Sleep(time.Second),
        chromedp.SetValue(`body>textarea:first-child`, "hello world!", chromedp.ByQuery),
        chromedp.Sleep(time.Second),
        chromedp.SetValue(`body>textarea:nth-child(2)`, "hello chromedp!", chromedp.ByQuery),
        chromedp.Sleep(3*time.Second),
    )
    if err != nil {
        panic(err)
    }
}
Zeke Lu
  • 6,349
  • 1
  • 17
  • 23
  • Ohhhh man, that is genious, I totally forgot about those pseudo selectors since I barely use them, ugh... thank you so much for your answer, really helped me out! – Angelo van Cleef Nov 21 '22 at 08:51
  • Unfortunately this does not work (not sure why, because they don't share the same parent?), I think the HTML is different for each wrapping div around the text area. So unfortunately body>textarea:nth-child(2) is not working. Any other tricks? – Angelo van Cleef Nov 22 '22 at 18:59
  • textarea:first-child is not working either unfortunately but "textarea" does work. – Angelo van Cleef Nov 22 '22 at 19:07
  • `body>textarea:nth-child(2)` selects the second **direct** child textarea of the `body` element. This is very unlikely working for you, so you could not copy it directly. Can you update your question to include the html so that I can provide a selector for that html? – Zeke Lu Nov 22 '22 at 22:46