How to use querySelector in Bucklescript

Sometimes, the Bucklescript-TEA library doesn’t give you what you are looking for and you want to directly access the DOM to manipulate items.

You usually go for something like this in Javascript using querySelector:

var element = document.querySelector("#id-selector");

Here’s how you can use querySelector in Bucklescript.

type doc
external document = doc = "" [@@bs.val]
external querySelector : doc -> string -> dom_element = "" [@@bs.send]

This gives you the ability to do this:

let element = document |. querySelector("#id-selector")

Which outputs the same Javascript as above.

After which, you can do whatever you want with it.

Here I’ll just use an example of adding a class to it.

So you need to setup another external for add function of classList. ( I do this in one statement here since I don’t need classList directly for anything else.)

external add : dom_element -> string -> unit = "" 
[@@bs.send][@@bs.scope "classList"]

Then you can use it like this:

let 
  element = document |. querySelector("#id-selector")
in
  if element = some_condition then
    element |. add "special-class"

Which would give you Javascript like this:

var element = document.querySelector("#" + position);
if (element === some_condition) {
  element.classList.add("special-class");
  return 0;
}

Not too bad, right?

Though in this case, Bucklescript-TEA already gives you a way to add classes to elements, so this may not be that useful. In a later post, I’ll show you an example of a scenario where Bucklescript-TEA can’t easily handle.

Comments