How to select a dom with a particular id?


#1

Hi all
How to select a dom with a particular id:

<div class="nav-menu fixed-top">

With JQUERY I would do like:

  function menuscroll() {
        var $navmenu = $('.nav-menu');
        if ($(window).scrollTop() > 50) {
            $navmenu.addClass('is-scrolling');
        } else {
            $navmenu.removeClass("is-scrolling");
        }
    }
    menuscroll();  

Thanks a lot.


#2

From BuckleScript docs:

type element;
[@bs.val] [@bs.return nullable] [@bs.scope "document"] external getElementById : string => option(element) = "getElementById";

When you use getElementById, it’ll implicitly convert the JS nullable string into an option. Saves you an explicit conversion through Js.Nullable.toOption.


#3

If you are using bs-webapi, you can do document.querySelector, which returns an option(Dom.element), or document.querySelectorAll, which returns a Dom.nodeList (In your example, you seem to be selecting by a CSS class, not by an id)

open Webapi.Dom;
let optMenu = Document.querySelector(".nav-menu", document);

#4

Also responded in your other thread:

/**
  * The module Jquery has external bindings to the DOM and JQuery.
  * See https://bucklescript.github.io/ for more info on externals.
  */
module Jquery = {
  type element;
  type domNode;
  [@bs.val] external window : domNode = "";
  [@bs.val] external select : string => element = "$";
  [@bs.val] external wrapDOMNode : domNode => element = "$";

  [@bs.send] external addClass : (element, string) => unit = "";
  [@bs.send] external removeClass: (element, string) => unit = "";
  [@bs.send] external scrollTop: (element, unit) => int = "";
};

let menuscroll = () => {
  let navmenu = Jquery.select(".nav-menu");
  let window = Jquery.wrapDOMNode(Jquery.window);

  if (Jquery.scrollTop(window, ()) > 50) {
    Jquery.addClass(navmenu, "is-scrolling");
  } else {
    Jquery.removeClass(navmenu, "is-scrolling");
  }
};