dennwc/dom

Getting an element value ?

Closed this issue · 3 comments

Trying to do the same thing as this issue => #6 but I think I still miss something ?
In my situation, I have input fields inside a form, can you provide a way to manipulate forms ?
I noticed that looping over the nodeList we got more elements than the actual form ? Any insight on that ?

form := dom.Doc.GetElementById("custom_form")
btn := dom.Doc.GetElementById("btn")
t := document.Call("getElementById", "target")
logger := log.New((*writer)(&t), "", log.LstdFlags)

btn.AddEventListener("click", func(_ dom.Event) {
	nodes := form.ChildNodes()
	for _, element := range nodes {
		logger.Print("ID: " + string(element.Id()) + " Value: " + string(element.JSValue().Get("value").String()))
	}
})

Child nodes include both text and element nodes - you're only interested in the element nodes. This behavior is correct according to the most recent specification (which deprecates attributes as child nodes) but might seem inconvenient. One way to achieve what you want is to change your for loop as follows:

	for _, element := range nodes {
		if element.TagName() != "" {
			logger.Print("ID: " + string(element.Id()) + " Value: " + string(element.JSValue().Get("value").String()))
		}
	}

A more correct test would be e.JSValue().Get("nodeType")) == 1 but this method is not currently wrapped by the NodeBase type. See https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType for enumerated node types.

After commit 61179be, the test in my previous comment can be written as e.NodeType() == ElementNode.

Thanks !