v2.0.3

Building DOM Elements

Last updated


Build real DOM elements from tag-selector strings and query elements with string getters.

First Render: Chainable DOM Construction


"tag.class#id"._(attrs, children) builds a real DOM element from a tag-selector string, handling SVG namespace and input/textarea type parsing automatically. The #id segment becomes the element's id; each .class segment is added to the class list with its leading dot ("p.note"._() gives class=".note"), so plain class names go through _class() or a class attribute. Where jQuery wraps matched elements in a jQuery object to chain its methods, RenderJS adds its methods to the native prototypes, so "section#test"._() and "test".$ return plain Element objects.
  1. <script>
  2. document.body._child(
  3. "section#test"._([
  4. "button"._({
  5. style: {
  6. width: "10rem",
  7. height: "2rem",
  8. backgroundColor: "steelblue",
  9. color: "#fff"
  10. }
  11. }, [
  12. "span"._("test"),
  13. " button"
  14. ])._click(function () {
  15. alert("test");
  16. }),
  17. "img"._({ lazyload: "/assets/cover.png", width: 160 }),
  18. "input@email type"._()
  19. ])
  20. );
  21. // Enable SVG inlining and image lazyload listeners
  22. _Listener({
  23. svg: true,
  24. lazyload: true
  25. });
  26. </script>
Live preview · @pardnchiu/renderjs@2.0.3

Element Querying


  1. <div id="test">#test</div>
  2. <div class="test">first .test</div>
  3. <div class="test">second .test</div>
  4. <pre id="out"></pre>
  5. <script>
  6. "out".$.textContent = [
  7. '"test".$ -> ' + "test".$.textContent,
  8. '"div.test".$ -> ' + "div.test".$.textContent,
  9. '"div.test".$all -> ' + "div.test".$all.length + " elements"
  10. ].join("\n");
  11. </script>
Live preview · @pardnchiu/renderjs@2.0.3

Full method lists: String Extensions and Element Extensions.
中文