How to Check If A Certain Element Exists in The DOM

JavaScript: How to check if an element exists in the DOM

When you need to check for the existence of a certain element in the DOM, you can use one of the following document selector methods as follows:

After you tried to retrieve the element using the selectors above, you can check if the specified element exists or not by checking the value returned by the methods.

Both querySelector() and getElementById() returns null when the element doesn’t exist, so you can check the result as follows:

if (document.getElementById("myDiv")) {
  console.log("Element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

if (document.querySelector("#myDiv")) {
  console.log("Element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

On the other hand, both getElementsByName() and getElementsByClassName() methods return an array, so you need to check the .length property and see if its value is greater than 0.

Here’s an example:

let elements = document.getElementsByName("paragraph");
if (elements.length) {
  console.log("At least one element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

And that’s how you can check whether an element exists in the DOM or not.

Original article source at: https://sebhastian.com/

#javascript #dom #check 

How to Check If A Certain Element Exists in The DOM
Oral  Brekke

Oral Brekke

1669190654

How The JavaScript AppendChild Method Works in The HTML DOM Tree

JavaScript Node appendChild() method explained - with code examples

The JavaScript appendChild() method is a method that’s available from the JavaScript Node object.

The method allows you to add a node as a child of the node where you call the method from. The given node will be added as the last child of the receiving node.

For example, you can append a <div> element to the <body> element using the following code:

let aDiv = document.createElement("div");

document.body.appendChild(div);

The end result is that the <div> will be added to the <body> tag:

<body>
  <div></div>
</body>

When the node already has a child node or more, the element will be added below the last child node.

For example, suppose you want to append a <span> element to the <body> tag above. Here’s the code you need to run:

let aSpan = document.createElement("span");
document.body.appendChild(span);

// Result:
<body>
  <div></div>
  <span></span>
</body>

The appendChild() method accepts only one argument: the Node object you want to append to the receiving node. This is usually an HTML element.

When you try to pass a string, JavaScript will throw a TypeError message like this:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node':
parameter 1 is not of type 'Node'.

Finally, if you use an existing Node in the DOM tree as the argument to the appendChild() method, that element will be moved from its current position to the new position.

Suppose you have the following DOM tree in your HTML document:

<body>
  <div id="wrapper">
    <p id="paragraph">
      <span id="span"></span>
    </p>
  </div>
</body>

You can move the <span> element as a child of the <body> tag with the appendChild() method.

You just need to get the existing element first, then pass that element into the appendChild() method as shown below:

let span = document.getElementById("span");
document.body.appendChild(span);

// Result:
<body>
  <div id="wrapper">
    <p id="paragraph"></p>
  </div>
  <span id="span"></span>
</body>

Finally, the appendChild() method returns the argument you passed into it back.

You can use the returned value to do other operations, such as adding a text to it:

document.body.appendChild(span).innerText = "Hello!";

// The same as:
document.body.appendChild(span);
span.innerText = "Hello!";

// Result:
<body>
  <div id="wrapper">
    <p id="paragraph"></p>
  </div>
  <span id="span">Hello!</span>
</body>

You can call an Element or Node object method by chaining it to the returned value of the appendChild() method.

And that’s how the JavaScript appendChild() method works. 😉

Original article source at: https://sebhastian.com/

#javascript #method #dom #tree 

How The JavaScript AppendChild Method Works in The HTML DOM Tree
Zenon  Pruschke

Zenon Pruschke

1669106554

How the DOM Works in JavaScript

In this tutorial, you'll learn what the DOM is and how it works in JavaScript. Understanding how the DOM and events work in JavaScript is key if you want to be an effective front end developer.

What is the DOM?

DOM stands for Document Object Model. It's the interface between JavaScript and the web browser.

With the help of the DOM, you can write JavaScript to create, modify, and delete HTML elements, set styles, classes and attributes, and listen and respond to events.

The DOM tree is generated from an HTML document, which you can then interact with. The DOM is a very complex API which has methods and properties to interact with the DOM tree.

Frame-70-1

Illustration of the DOM

You can visualize the DOM tree here.

How the DOM Works – Behind the Scenes

The DOM is organized in a really clever manner. The parent element is called the EventTarget. You can understand better how it works with the help of the below diagram:

DOM-behind-the-scene-1

The EventTarget interface is implemented by objects which can receive events and may have listeners for them. In other words, any target of events implements the three methods associated with this interface. Element, and its children, as well as Document and Window are the most common event targets, but other objects can be event targets, too.

Window represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object. Even the document object (of the HTML DOM) is a property of the window object.

window.document.getElementById("header");

// Both are same

document.getElementById("header");

Nodes are in the DOM aka Document Object model. In the DOM, all parts of the document, such as elements, attributes, text, and so on are organized in a hierarchical tree-like structure that consists of parents and children. These individual parts of the document are known as nodes.

The Node in the above diagram is represented by a JavaScript object. We mostly work with the document which has most commonly used methods like document.queryselector(), document.getElementBy Id(), and so on.

Now we will take a look at the document.

How to Select, Create, and Delete Elements Using the DOM

With the help of the DOM, we can select, delete, and create element in JavaScript.

How to Select Elements

There are multiple ways we can select HTML elements in JavaScript. These are the methods we'll look at here:

  • document.getElementById();
  • document.getElementByClassName();
  • document.getElementByTagName();
  • document.querySelector();
  • document.querySelectorAll();

How to use the document.getElementById() method

The getElementById() method returns an element whose id matches a passed string. Since the ids of HTML elements are supposed to be unique, this is a faster way to select an element with ids.

Example:

const ele = document.getElementById("IDName");
console.log(ele); // This will log the whole HTML element

How to use the document.getElementByClassName() method

The document.getElementByClassName() method returns an HTMLCollection of elements that match the passed class's name. We can search for multiple class names by passing the class names separated by whitespaces. It will return a live HTMLCollection.

So what does it mean that the HTMLCollection is "live"? Well, it means that once we get the HTMLCollection for a class name, if we add an element with the same class name, then the HTMLCollection gets updated automatically.

Example:

const ele = document.getElementByClassName("ClassName");
console.log(ele); // Logs Live HTMLCollection

How to use the document.getElementByTagName(); method

The document.getElementByTagName() method returns the HTMLCollection of elements that match the passed tag name. It can be called on any HTML element. It returns an HTMLCollection which is a live collection.

Example:

const paragraph = document.getElementByTagName("p");
const heading = document.getElementByTagName("h1");

console.log(paragraph); // p element HTMLCollection
console.log(heading); // h1 element HTMLCollection

How to use the document.querySelector() method

The document.querySelector() method returns the first element that matches the passed selector. Now here, we can pass classname, id, and tagname. Take a look at the below example:

const id = document.querySelector("#idname"); // using id
const classname = document.querySelector(".classname"); // using class
const tag = document.querySelector("p"); // using tagname

Rules for selection:

  • When selecting using class, use (.) at the start. For example (".classname")
  • When selecting using id, use (#) at the start. For example ("#id")
  • When selecting using a tag, simply select directly. For example ("p")

How to use the document.querySelectorAll() method

The document.querySelectorAll() method is an extension of the querySelector method. This method returns all the elements that match the passed selector. It returns the Nodelist collection which is not live.

const ele = document.querySelectorAll("p");
console.log(ele); // return nodelist collection of p tag

NOTE: HTMLCollection is a live collection, while the Nodelist collection is a static collection.

How to Create Elements

You can create HTML elements in JavaScript and add them to HTML dynamically. You can create any HTML element with document.createElement() by passing the tag name in parenthesis.

After you create the element, you can add the classname, attributes and textcontent to that element.

Here's an example:

const ele = document.createElement("a");
ele.innerText = "Click Me";
ele.classList.add("text-left");
ele.setAttribute("href", "www.google.com");

// update to existing element in HTML
document.querySelector(".links").prepend(ele);
document.querySelector(".links").append(ele);
document.querySelector(".links").befor(ele);
document.querySelector(".links").after(ele);

// Simalar to below anchor tag
// <a href="www.google.com">Click Me</a>

In the above example, we created an anchor tag in JavaScript and added attributes and a classname to that anchor tag. We have four methods in the above example to update the created element in the HTML.

  • prepend(): inserts the data at the top of its first child element.
  • append(): inserts the data or content inside an element at the last index.
  • before(): inserts the data before the selected element.
  • after(): puts the element after the specified element. Or you can say that it inserts data outside an element (making the content its sibling) in the set of matched elements.

How to Delete Elements

We know how to create elements in JavaScript and push them to the HTML. But what if we want to delete existing elements in the HTML? It's easy – we just need to use the remove() method on that element.

Here's an example:

const ele = document.querySelector("p");

// This will remove ele when clicked on
ele.addEventListner('click', function(){
	ele.remove();
})

How to Manipulate CSS from JavaScript

We know how to manipulate HTML from JavaScript. Now we will learn how to manipulate CSS from JavaScript. This can help you change the styling of your web pages dynamically.

For example, if you click on an element, its background color should change. This is possible by manipulating CSS from JavaScript.

Here's some example syntax:

const ele = document.querySelector("desired element");

ele.style.propertyName = value;

// E.g -
ele.style.color = red;

When changing CSS properties using JavaScript, you need to make sure whenever there is a - in the CSS, you capitalize the next letter. For example, in CSS you would write background-color, but in JavaScript, backgroundColor (with a capital C).

Here's an example:

const ele = document.querySelector("div");
ele.style.backgroundColor = "red";

Now suppose you already wrote CSS for your project and you wanted to add classes using JavaScript. We can do that using classList in JavaScript.

Here's an example:

const ele = document.querySelector(".link");
ele.classList.add("bg-red"); // add class bg-red to existing class list
ele.classList.remove("pb-4");// remove class bg-red from existing class list
ele.classList.toggle("bg-green"); // toggle class bg-red to existing class list which means if it already exists then it will be removed, if it doesn't exist it will be added.

When we use classList it adds, removes, or toggles classes directly to the element. It's like updating with existing classes.

Unlike element.className it removes all existing classes and adds the given class.

Here's an example:

const ele = document.querySelector(".link");
ele.classList.add("bg-red"); // add class bg-red to existing class list
ele.classList.remove("pb-4");// remove class bg-red from existing class list

ele.className = "p-10"; // Now this will remove all existing classes and add only "p-10 class to element."

How to Use Event Handlers

The change in the state of an object is known as an Event. The process of reacting to the events is called Event Handling.

Events happen when a user does something like click, hover over an element, press a key, and so on. So when an event happens and you want to do a certain thing or manipulate anything, you use event handlers to trigger that event.

We use event handlers to execute certain code when that particular event happens. There are multiple event handlers in JavaScript (here's a quick list of them), but you use the same process to add event handlers to any element.

Here's the syntax:

const ele = document.querySelector("a");

ele.addEventListner("event", function(){
	// callback function
});

Some events you can use:

  • click
  • mouseover
  • mouseout
  • keypress
  • keydown

And here's an example of using the "click" event:

const ele = document.querySelector("a");

ele.addEventListner("click", function(){
	ele.style.backgroundColor = "pink";
});

Event Propagation: Bubbling and Capturing

Event Propagation determines in which order the elements receive the event(s). There are two ways to handle this event propagation order in the DOM: Event Bubbling and Event Capturing.

Frame-71-1

What is Event Bubbling?

When an event happens on a component, it first runs the event handler on it, then on its parent component, then all the way up on the other ancestors’ components.

By default, all event handlers move through this order from center component event to outermost component event.

What is Event Capturing?

This is the opposite of bubbling. The event handler acts first on its parent component and then on the component where it was actually meant to fire.

In short, this means that the event is first captured by the outermost element and propagated to the inner elements. It is also called trickle down.

Let's try the below example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
    <style>
        nav{
            display: flex;
            justify-content: center;
            padding: 30px;
        }

        nav li{
            list-style: none;
            padding: 5px;
        }

        nav li a{
            text-decoration: none;
            padding: 20px;
        }
    </style>
</head>
<body>
    
    <div>
        <nav>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </nav>
    </div>

    <script>
        const navbar = document.querySelector("nav");
        navbar.addEventListener('click', function(){
            navbar.style.backgroundColor="green"
        });

        const anchor = document.querySelector("a");
        anchor.addEventListener("click", function(){
            anchor.style.backgroundColor="pink";
        })
    </script>
</body>
</html>

This code gives us the following:

Screenshot-2022-09-26-142920

Now study above example carefully. I have added an event listener to the nav tag and to the anchor tag. When you click on nav, the background color changes to green. When you click on the anchor tag, the background color changes to pink.

But when you click on the anchor tag, the background color of anchor as well as nav changes. This is because of event bubbling.

This is what happens when you only click on the nav element:

Frame-72--1-

This is what happens when you only click on the nav element.

This is what happens when you only click on the anchor element:

Frame-73--1-

This is what happens when you only click on the anchor element

To stop event propagation, we can use stoppropagation() on the event listener because of which the event propagation is happing. It will prevent the nav element event listener from getting activated in the above example.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Example</title>
    <style>
        nav{
            display: flex;
            justify-content: center;
            padding: 30px;
        }

        nav li{
            list-style: none;
            padding: 5px;
        }

        nav li a{
            text-decoration: none;
            padding: 20px;
        }
    </style>
</head>
<body>
    
    <div>
        <nav>
            <li><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
        </nav>
    </div>

    <script>
        const navbar = document.querySelector("nav");
        navbar.addEventListener('click', function(){
            navbar.style.backgroundColor="green"
        });

        const anchor = document.querySelector("a");
        anchor.addEventListener("click", function(e){
            e.stopPropagation();
            anchor.style.backgroundColor="pink";
        })
    </script>
</body>
</html>

How to Traverse the DOM

"A good JavaScript developer needs to know how to traverse the DOM— it’s the act of selecting an element from another element. " – Zell Liew

Now we are going to see why traversing the DOM is better than using the document.querySelector() method, and how to traverse like a pro.

There are 3 ways to traverse the DOM:

  • Upward
  • Downward
  • Sideways

How to traverse the DOM upward

There are two methods which help you traverse the DOM upward:

  • parentElement
  • closest

parentElement is a property that selects the parent element, like this:

const ele = document.querySelector("a");
console.log(ele.parentElement); // <div>

The parentElement is great for selecting one level upwards. But closest lets you find an element that can be multiple levels above the current element. closest lets you select the closest ancestor element that matches a selector.

Here's an example of using closest:

<div>
    <h3 class="demo">This is sample</h3>
    <h1 class="demo">This is heading</h1>
    <h2 class="heading"> This heading 2</h2>
</div>
const ele = document.querySelector(".heading");
console.log(ele.closest(".demo")); // This is heading

In above code we are trying to get closest element to .heading which has a class of .demo.

How to traverse the DOM downward

We can traverse downward using the children method on a selector. With children you can select direct child of selected element.

Here's an example:

<div>
    <a href="#">Link-1</a>
    <a href="#">Link-2</a>
    <a href="#">Link-3</a>
    <a href="#">Link-4</a>
</div>
const ele = document.querySelector("div");
const child = ele.children;

console.log(child); // gives HTMLCollection
// 4 element inside div

How to traverse the DOM sideways

It's very interesting to traverse the DOM sideways. There are mainly two methods we can use:

  • previousElementSibling
  • nextElementSibling

With the help of the previousElementSibling method, we can select previous elements in the HTML like this:

<div>
    <a href="#">Link-1</a>
    <h1>Heading</h1>
</div>
const ele = document.querySelector("h1");
console.log(ele.previousElementSibling); // <a href="#">Link-1</a>

With the help of nextElementSibling, we can select the next element in the HTML like this:

<div>
    <a href="#">Link-1</a>
    <h1>Heading</h1>
</div>
const ele = document.querySelector("a");
console.log(ele.nextElementSibling); // <h1>Heading</h1>

Wrapping Up

I hope you now understand how the DOM works in JavaScript. Thank you for reading!

Original article source at https://www.freecodecamp.org

#javascript #js #dom 

How the DOM Works in JavaScript
Oral  Brekke

Oral Brekke

1669018804

How to Fix ReactDOM is Not Defined Error

Here's how to fix ReactDOM is not defined error

When you encounter an error saying ‘ReactDOM’ is not defined, it means that your application is can’t find the variable ReactDOM because it hasn’t been initialized yet.

Most likely, you forgot to import it from the package react-dom:

import ReactDOM from 'react-dom'

Or if you use ES5:

const ReactDOM = require('react-dom')

If you have the import but still got the error, check the letter case of both your import and your code that calls the variable. Make sure it’s exactly the same case. In the example below, the variable is called as ReactDom while the import is defined as ReactDOM. This will not work:

import ReactDOM from 'react-dom'

ReactDom.render()

Generally, “X is not defined error” is caused by wrong import and different letter case between import and the imported variable call. The error isn’t React specific, but a regular JavaScript import and export error.

Original article source at: https://sebhastian.com/

#react #dom #error 

How to Fix ReactDOM is Not Defined Error
Lawrence  Lesch

Lawrence Lesch

1667920860

HTML-dom: Common Tasks Of Managing HTML DOM with Vanilla JavaScript

HTML DOM

Story

Web development goes very fast. I still remember the moments when starting to use jQuery, Prototype, script.aculo.us, Zepto and many more.

Nowadays, even if our application is powered by modern tools such as Angular, Vue, React, Svelte, .etc, we have to deal with DOM. The frameworks encapsulate and hide the DOM management directly, but still give us a door to work with DOM via ref, event handlers.

If you develop or use a web component in any framework, you have to work with DOM at a certain level.

Knowing the browser DOM APIs and how to use them play an important role in web development. A website introducing the APIs, well-known problems, most popular questions could be very useful.

Features

  •  No external library. Only native browsers' APIs
  •  Small and easy to understand examples
  •  Live demos
  •  Many tips and good practices included
  •  Many real use cases
  •  Work with the modern browsers. Try to support IE 11

Running it on local

Clone the project:

$ git clone https://github.com/phuocng/html-dom

Install the dependencies:

$ cd html-dom
$ npm install

Run it on the local:

$ npm run start

Open http://localhost:8081 in your browser to see it in action.

About

This project is developed by Nguyen Huu Phuoc. I love building products and sharing knowledge.

Be my friend on

Download Details:

Author: Phuocng
Source Code: https://github.com/phuocng/html-dom 
License: MIT license

#typescript #javascript #html #dom 

HTML-dom: Common Tasks Of Managing HTML DOM with Vanilla JavaScript
Lawrence  Lesch

Lawrence Lesch

1667809800

Cash: An Absurdly Small JQuery Alternative for Modern Browsers

Cash

Cash is an absurdly small jQuery alternative for modern browsers (IE11+) that provides jQuery-style syntax for manipulating the DOM. Utilizing modern browser features to minimize the codebase, developers can use the familiar chainable methods at a fraction of the file size. 100% feature parity with jQuery isn't a goal, but Cash comes helpfully close, covering most day to day use cases.

Comparison

SizeCashZepto 1.2.0jQuery Slim 3.4.1
Unminified36.5 KB58.7 KB227 KB
Minified16 KB26 KB71 KB
Minified & Gzipped6 KB9.8 KB24.4 KB

A 76.6% gain in size reduction compared to jQuery. If you need a smaller bundle, we support partial builds too.

FeaturesCashZepto 1.2.0jQuery Slim 3.4.1
Supports Older Browsers️❌
Supports Modern Browsers️✔
Actively Maintained
Namespaced Events️❌
Typed Codebase✔ (TypeScript)️❌
TypeScript Types✔ (generated from code)⚠️ (via DefinitelyTyped)⚠️ (via DefinitelyTyped)
Partial Builds✔ (can exclude individual methods)⚠️ (can exclude whole modules)⚠️ (can exclude whole modules)

If you're migrating from jQuery be sure to read our migration guide.

Usage

Get Cash from CloudFlare or jsDelivr and use it like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/cash/8.1.1/cash.min.js"></script>
<script>
  $(function () {
    $('html').addClass ( 'dom-loaded' );
    $('<footer>Appended with Cash</footer>').appendTo ( document.body );
  });
</script>

Cash is also available through npm as the cash-dom package:

npm install --save cash-dom

That you can then use like this:

import $ from "cash-dom";

$(function () {
  $('html').addClass ( 'dom-loaded' );
  $('<footer>Appended with Cash</footer>').appendTo ( document.body );
});

Documentation

Cash gives you a query selector, collection methods and some library methods. If you need more details about our API just check out jQuery's, while we don't implement everything that jQuery provides, everything what we do implement should be compatible with jQuery. Cash can be extended with custom methods, read how here.

$()

This is the main selector method for Cash. It returns an actionable collection of nodes.

If a function is provided, the function will be run once the DOM is ready.

$( selector [, element] ) // => collection, using `element` as the context
$( selector [, collection] ) // => collection, using `collection` as the context
$(node) // => collection
$(nodeList) // => collection
$(htmlString) // => collection
$(collection) // => self
$(function () {}) // => document ready callback

Collection Methods

These methods from the collection prototype ($.fn) are available once you create a collection with $() and are called like so:

$(element).addClass ( className ) // => collection

Some extra methods are available but disabled by default.

AttributesCollectionCSSDataDimensionsEffects
fn.addClass ()fn.add ()fn.css ()fn.data ()fn.height ()fn.hide ()
fn.attr ()fn.each ()  fn.innerHeight ()fn.show ()
fn.hasClass ()fn.eq ()  fn.innerWidth ()fn.toggle ()
fn.prop ()fn.filter ()  fn.outerHeight () 
fn.removeAttr ()fn.first ()  fn.outerWidth () 
fn.removeClass ()fn.get ()  fn.width () 
fn.removeProp ()fn.index ()    
fn.toggleClass ()fn.last ()    
 fn.map ()    
 fn.slice ()    
EventsFormsManipulationOffsetTraversal
fn.off ()fn.serialize ()fn.after ()fn.offset ()fn.children ()
fn.on ()fn.val ()fn.append ()fn.offsetParent ()fn.closest ()
fn.one () fn.appendTo ()fn.position ()fn.contents ()
fn.ready () fn.before () fn.find ()
fn.trigger () fn.clone () fn.has ()
  fn.detach () fn.is ()
  fn.empty () fn.next ()
  fn.html () fn.nextAll ()
  fn.insertAfter () fn.nextUntil ()
  fn.insertBefore () fn.not ()
  fn.prepend () fn.parent ()
  fn.prependTo () fn.parents ()
  fn.remove () fn.parentsUntil ()
  fn.replaceAll () fn.prev ()
  fn.replaceWith () fn.prevAll ()
  fn.text () fn.prevUntil ()
  fn.unwrap () fn.siblings ()
  fn.wrap ()  
  fn.wrapAll ()  
  fn.wrapInner ()  

$.fn

The main prototype for collections, allowing you to extend Cash with plugins by adding methods to all collections.

$.fn // => Cash.prototype
$.fn.myMethod = function () {}; // Custom method added to all collections
$.fn.extend ( object ); // Add multiple methods to the prototype

fn.add ()

Returns a new collection with the element(s) added to the end.

$(element).add ( element ) // => collection
$(element).add ( selector ) // => collection
$(element).add ( collection ) // => collection

fn.addClass ()

Adds the className class to each element in the collection.

Accepts space-separated className for adding multiple classes.

$(element).addClass ( className ) // => collection

fn.after ()

Inserts content or elements after the collection.

$(element).after ( element ) // => collection
$(element).after ( htmlString ) // => collection
$(element).after ( content [, content] ) // => collection

fn.append ()

Appends content or elements to each element in the collection.

$(element).append ( element ) // => collection
$(element).append ( htmlString ) // => collection
$(element).append ( content [, content] ) // => collection

fn.appendTo ()

Adds the elements in the collection to the target element(s).

$(element).appendTo ( element ) // => collection

fn.attr ()

Without attrValue, returns the attribute value of the first element in the collection.

With attrValue, sets the attribute value of each element of the collection.

$(element).attr ( attrName ) // value
$(element).attr ( attrName, attrValue ) // => collection
$(element).attr ( object ) // => collection

fn.before ()

Inserts content or elements before the collection.

$(element).before ( element ) // => collection
$(element).before ( htmlString ) // => collection
$(element).before ( content [, content] ) // => collection

fn.children ()

Without a selector specified, returns a collection of child elements.

With a selector, returns child elements that match the selector.

$(element).children () // => collection
$(element).children ( selector ) // => collection

fn.closest ()

Returns the closest matching selector up the DOM tree.

$(element).closest ( selector ) // => collection

fn.contents ()

Get the children of each element in the set of matched elements, including text and comment nodes.

Useful for selecting elements in friendly iframes.

$('iframe').contents ().find ( '*' ) // => collection

fn.clone ()

Returns a collection with cloned elements.

$(element).clone () // => collection

fn.detach ()

Removes collection elements, optionally that match the selector, from the DOM.

$(element).detach () // => collection
$(element).detach ( selector ) // => collection

fn.css ()

Returns a CSS property value when just property is supplied.

Sets a CSS property when property and value are supplied.

Sets multiple properties when an object is supplied.

Properties will be autoprefixed if needed for the user's browser.

$(element).css ( property ) // => value
$(element).css ( property, value ) // => collection
$(element).css ( object ) // => collection

fn.data ()

Without arguments, returns an object mapping all the data-* attributes to their values.

With a key, return the value of the corresponding data-* attribute.

With both a key and value, sets the value of the corresponding data-* attribute to value.

Multiple data can be set when an object is supplied.

$(element).data () // => object
$(element).data ( key ) // => value
$(element).data ( key, value ) // => collection
$(element).data ( object ) // => collection

fn.each ()

Iterates over a collection with callback ( index, element ). The callback function may exit iteration early by returning false.

$(element).each ( callback ) // => collection

fn.empty ()

Empties the elements interior markup.

$(element).empty () // => collection

fn.eq ()

Returns a collection with the element at index.

$(element).eq ( index ) // => collection

fn.extend ()

Adds properties to the Cash collection prototype.

$.fn.extend ( object ) // => object

fn.filter ()

Returns the collection that results from applying the filter selector/method.

$(element).filter ( selector ) // => collection
$(element).filter ( function ( index, element ) {} ) // => collection

fn.find ()

Returns selector match descendants from the first element in the collection.

$(element).find ( selector ) // => collection

fn.first ()

Returns a collection containing only the first element.

$(element).first () // => collection

fn.get ()

Returns the element at the index, or returns all elements.

$(element).get ( index ) // => domNode
$(element).get () // => domNode[]

fn.has ()

Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

$(element).has ( selector ) // => collection
$(element).has ( element ) // => collection

fn.hasClass ()

Returns the boolean result of checking if any element in the collection has the className attribute.

$(element).hasClass ( className ) // => boolean

fn.height ()

Returns or sets the height of the element.

$(element).height () // => Integer
$(element).height ( number ) // => collection

fn.hide ()

Hide the elements.

$(element).hide () // => collection

fn.html ()

Returns the HTML text of the first element in the collection, sets the HTML if provided.

$(element).html () // => HTML Text
$(element).html ( htmlString ) // => HTML Text

fn.index ()

Returns the index of the element in its parent if an element or selector isn't provided. Returns index within element or selector if it is.

$(element).index () // => Integer
$(element).index ( element ) // => Integer

fn.innerHeight ()

Returns the height of the element + padding.

$(element).innerHeight () // => Integer

fn.innerWidth ()

Returns the width of the element + padding.

$(element).innerWidth () // => Integer

fn.insertAfter ()

Inserts collection after specified element.

$(element).insertAfter ( element ) // => collection

fn.insertBefore ()

Inserts collection before specified element.

$(element).insertBefore ( element ) // => collection

fn.is ()

Returns whether the provided selector, element or collection matches any element in the collection.

$(element).is ( selector ) // => boolean

fn.last ()

Returns a collection containing only the last element.

$(element).last () // => collection

fn.map ()

Returns a new collection, mapping each element with callback ( index, element ).

$(selector).map ( callback ) // => collection

fn.next ()

Returns the next adjacent elements.

$(element).next () // => collection
$(element).next ( selector ) // => collection

fn.nextAll ()

Returns all the next elements.

$(element).nextAll () // => collection
$(element).nextAll ( selector ) // => collection

fn.nextUntil ()

Returns all the next elements, until the provided selector matches.

$(element).nextUntil ( selector ) // => collection
$(element).nextUntil ( selector, filterSelector ) // => collection

fn.not ()

Filters collection by false match on collection/selector.

$(element).not ( selector ) // => collection
$(element).not ( collection ) // => collection

fn.off ()

Removes event listener from collection elements.

Accepts space-separated eventName for removing multiple events listeners.

Removes all event listeners if called without arguments.

$(element).off ( eventName, eventHandler ) // => collection
$(element).off ( eventName ) // => collection
$(element).off ( eventsMap ) // => collection
$(element).off () // => collection

fn.offset ()

Get the coordinates of the first element in a collection relative to the document.

$(element).offset () // => Object

fn.offsetParent ()

Get the first element's ancestor that's positioned.

$(element).offsetParent () // => collection

fn.on ()

Adds event listener to collection elements.

Accepts space-separated eventName for listening to multiple events.

Event is delegated if delegate is supplied.

$(element).on ( eventsMap ) // => collection
$(element).on ( eventName, eventHandler ) // => collection
$(element).on ( eventName, delegate, eventHandler ) // => collection

fn.one ()

Adds event listener to collection elements that only triggers once for each element.

Accepts space-separated eventName for listening to multiple events.

Event is delegated if delegate is supplied.

$(element).one ( eventName, eventHandler ) // => collection
$(element).one ( eventName, delegate, eventHandler ) // => collection

fn.outerHeight ()

Returns the outer height of the element. Includes margins if includeMargings is set to true.

$(element).outerHeight () // => Integer
$(element).outerHeight ( includeMargins ) // => Integer

fn.outerWidth ()

Returns the outer width of the element. Includes margins if includeMargings is set to true.

$(element).outerWidth () // => Integer
$(element).outerWidth ( includeMargins ) // => Integer

fn.parent ()

Returns collection of elements who are parent of elements.

$(element).parent () // => collection
$(element).parent ( selector ) // => collection

fn.parents ()

Returns collection of elements who are parents of elements. Optionally filtering by selector.

$(element).parents () // => collection
$(element).parents ( selector ) // => collection

fn.parentsUntil ()

Returns collection of elements who are parents of elements, until a provided selector matches. Optionally filtering by selector.

$(element).parentsUntil ( selector ) // => collection
$(element).parentsUntil ( selector, filterSelector ) // => collection

fn.position ()

Get the coordinates of the first element in a collection relative to its offsetParent.

$(element).position () // => object

fn.prepend ()

Prepends content or elements to the each element in collection.

$(element).prepend ( element ) // => collection
$(element).prepend ( htmlString ) // => collection
$(element).prepend ( content [, content] ) // => collection

fn.prependTo ()

Prepends elements in a collection to the target element(s).

$(element).prependTo ( element ) // => collection

fn.prev ()

Returns the previous adjacent elements.

$(element).prev () // => collection
$(element).prev ( selector ) // => collection

fn.prevAll ()

Returns all the previous elements.

$(element).prevAll () // => collection
$(element).prevAll ( selector ) // => collection

fn.prevUntil ()

Returns all the previous elements, until the provided selector matches.

$(element).prevUntil ( selector ) // => collection
$(element).prevUntil ( selector, filterSelector ) // => collection

fn.prop ()

Returns a property value when just property is supplied.

Sets a property when property and value are supplied, and sets multiple properties when an object is supplied.

$(element).prop ( property ) // => property value
$(element).prop ( property, value ) // => collection
$(element).prop ( object ) // => collection

fn.ready ()

Calls callback method on DOMContentLoaded.

$(document).ready ( callback ) // => collection/span

fn.remove ()

Removes collection elements, optionally that match the selector, from the DOM and removes all their event listeners.

$(element).remove () // => collection
$(element).remove ( selector ) // => collection

fn.replaceAll ()

This is similar to fn.replaceWith (), but with the source and target reversed.

$(element).replaceAll ( content ) // => collection

fn.replaceWith ()

Replace collection elements with the provided new content.

$(element).replaceWith ( content ) // => collection

fn.removeAttr ()

Removes attribute from collection elements.

Accepts space-separated attrName for removing multiple attributes.

$(element).removeAttr ( attrName ) // => collection

fn.removeClass ()

Removes className from collection elements.

Accepts space-separated className for adding multiple classes.

Providing no arguments will remove all classes.

$(element).removeClass () // => collection
$(element).removeClass ( className ) // => collection

fn.removeProp ()

Removes property from collection elements.

$(element).removeProp ( propName ) // => collection

fn.serialize ()

When called on a form, serializes and returns form data.

$(form).serialize () // => String

fn.show ()

Show the elements.

$(element).show () // => collection

fn.siblings ()

Returns a collection of sibling elements.

$(element).siblings () // => collection
$(element).siblings ( selector ) // => collection

fn.slice ()

Returns a new collection with elements taken from start to end.

$(selector).slice ( start, end ) // => collection

fn.text ()

Returns the inner text of the first element in the collection, sets the text if textContent is provided.

$(element).text () // => text
$(element).text ( textContent ) // => collection

fn.toggle ()

Hide or show the elements.

$(element).toggle () // => collection

fn.toggleClass ()

Adds or removes className from collection elements based on if the element already has the class.

Accepts space-separated classNames for toggling multiple classes, and an optional force boolean to ensure classes are added (true) or removed (false).

$(element).toggleClass ( className ) // => collection
$(element).toggleClass ( className, force ) // => collection

fn.trigger ()

Triggers supplied event on elements in collection. Data can be passed along as the second parameter.

$(element).trigger ( eventName ) // => collection
$(element).trigger ( eventObj ) // => collection
$(element).trigger ( eventName, data ) // => collection
$(element).trigger ( eventObj, data ) // => collection

fn.unwrap ()

Removes the wrapper from all elements.

$(element).unwrap () // => collection

fn.val ()

Returns an inputs value. If value is supplied, sets all inputs in collection's value to the value argument.

$(input).val () // => value
$(input).val ( value ) // => collection

fn.width ()

Returns or sets the width of the element.

$(element).width () // => number
$(element).width ( number ) // => collection

fn.wrap ()

Wraps a structure around each element.

$(element).wrap ( structure ) // => collection

fn.wrapAll ()

Wraps a structure around all elements.

$(element).wrapAll ( structure ) // => collection

fn.wrapInner ()

Wraps a structure around all children.

$(element).wrapInner ( structure ) // => collection

Cash Methods

These methods are exported from the global $ object, and are called like so:

$.isArray ( arr ) // => boolean

Some extra methods are available but disabled by default.

Type CheckingUtilities
$.isArray ()$.guid
$.isFunction ()$.each ()
$.isNumeric ()$.extend ()
$.isPlainObject ()$.parseHTML ()
$.isWindow ()$.unique ()

$.guid

A unique number.

$.guid++ // => number

$.each ()

Iterates through an array and calls the callback ( index, element ) method on each element.

Iterates through an object and calls the callback ( key, value ) method on each property.

The callback function may exit iteration early by returning false.

$.each ( array, callback ) // => array
$.each ( object, callback ) // => object

$.extend ()

Extends target object with properties from the source object, potentially deeply too.

$.extend ( target, source ) // => object
$.extend ( true, target, source ) // => object

$.isArray ()

Check if the argument is an array.

$.isArray ([ 1, 2, 3 ]) // => true

$.isFunction ()

Check if the argument is a function.

function fn () {};
$.isFunction ( fn ) // => true

$.isNumeric ()

Check if the argument is numeric.

$.isNumeric ( 57 ) // => true

$.isPlainObject ()

Check if the argument is a plain object.

$.isPlainObject ( {} ) // => true

$.isWindow ()

Check if the argument is a Window object.

$.isWindow ( window ) // => true

$.parseHTML ()

Returns a collection from an HTML string.

$.parseHTML ( htmlString ) // => collection

$.unique ()

Returns a new array with duplicates removed.

$.unique ( array ) // => array

Contributing

If you found a problem, or have a feature request, please open an issue about it.

If you want to make a pull request you should:

  1. Clone the repository: git clone https://github.com/fabiospampinato/cash.git.
  2. Enter the cloned repository: cd cash
  3. Install the dependencies: npm install.
  4. Automatically recompile Cash whenever a change is made: npm run dev.
  5. Automatically rerun the tests whenever a change is made: npm run test:watch.
  6. Remember to update the readme, if necessary.

Thanks

Download Details:

Author: Fabiospampinato
Source Code: https://github.com/fabiospampinato/cash 
License: MIT license

#typescript #javascript #jquery #dom 

Cash: An Absurdly Small JQuery Alternative for Modern Browsers
Sean Wade

Sean Wade

1667366479

Everything You Need to Know About JavaScript DOM

In this tutorial, you'll learn about JavaScript DOM. DOM manipulation skill comes in handy a lot of times for web developers. You can read elements, change them, add more elements, change their style, traverse elements, listen to events on certain elements and more!

What you’ll learn:

  •        JavaScript DOM
  •        Getting elements by ID, Class and Tagnames
  •        Query Selectors
  •        Event Listeners
  •        Adding and deleting elements to and from the DOM
  •        Traversing the DOM

Are there any course requirements or prerequisites?

  •        HTML basics
  •        CSS basics
  •        JavaScript basics

Who this course is for:

  •        Web developers who want to learn how to manipulate the DOM
  •        Web developers who are new to DOM

#javascript #dom #programming 

Everything You Need to Know About JavaScript DOM
Rupert  Beatty

Rupert Beatty

1667041740

SwiftUI-compatible Framework for Building Browser App with WebAssembly

Tokamak

SwiftUI-compatible framework for building browser apps with WebAssembly 

At the moment Tokamak implements a very basic subset of SwiftUI. Its DOM renderer supports a few view types and modifiers (you can check the current list in the progress document), and a new HTML view for constructing arbitrary HTML. The long-term goal of Tokamak is to implement as much of SwiftUI API as possible and to provide a few more helpful additions that simplify HTML and CSS interactions.

If there's some SwiftUI API that's missing but you'd like to use it, please review the existing issues and PRs to get more details about the current status, or create a new issue to let us prioritize the development based on the demand. We also try to make the development of views and modifiers easier (with the help from the HTML view, see the example below), so pull requests are very welcome! Don't forget to check the "Contributing" section first.

If you'd like to participate in the growing SwiftWasm community, you're also very welcome to join our Discord server, or the #webassembly channel in the SwiftPM Slack.

Example code

Tokamak API attempts to resemble SwiftUI API as much as possible. The main difference is that you use import TokamakShim instead of import SwiftUI in your files. The former makes your views compatible with Apple platforms, as well as platforms supported by Tokamak (currently only WebAssembly/WASI with more coming in the future):

import TokamakShim

struct Counter: View {
  @State var count: Int
  let limit: Int

  var body: some View {
    if count < limit {
      VStack {
        Button("Increment") { count += 1 }
        Text("\(count)")
      }
      .onAppear { print("Counter.VStack onAppear") }
      .onDisappear { print("Counter.VStack onDisappear") }
    } else {
      VStack { Text("Limit exceeded") }
    }
  }
}

@main
struct CounterApp: App {
  var body: some Scene {
    WindowGroup("Counter Demo") {
      Counter(count: 5, limit: 15)
    }
  }
}

Arbitrary HTML

With the HTML view you can also render any HTML you want, including inline SVG:

struct SVGCircle: View {
  var body: some View {
    HTML("svg", ["width": "100", "height": "100"]) {
      HTML("circle", [
        "cx": "50", "cy": "50", "r": "40",
        "stroke": "green", "stroke-width": "4", "fill": "yellow",
      ])
    }
  }
}

HTML doesn't support event listeners, and is declared in the TokamakStaticHTML module, which TokamakDOM re-exports. The benefit of HTML is that you can use it for static rendering in libraries like TokamakVapor and TokamakPublish.

Another option is the DynamicHTML view provided by the TokamakDOM module, which has a listeners property with a corresponding initializer parameter. You can pass closures that can handle onclick, onmouseover and other DOM events for you in the listeners dictionary. Check out MDN docs for the full list.

An example of mouse events handling with DynamicHTML would look like this:

struct MouseEventsView: View {
  @State var position: CGPoint = .zero
  @State var isMouseButtonDown: Bool = false

  var body: some View {
    DynamicHTML(
      "div",
      ["style": "width: 200px; height: 200px; background-color: red;"],
      listeners: [
        "mousemove": { event in
          guard
            let x = event.offsetX.jsValue.number,
            let y = event.offsetY.jsValue.number
          else { return }

          position = CGPoint(x: x, y: y)
        },
        "mousedown": { _ in isMouseButtonDown = true },
        "mouseup": { _ in isMouseButtonDown = false },
      ]
    ) {
      Text("position is \(position), is mouse button down? \(isMouseButtonDown)")
    }
  }
}

Arbitrary styles and scripts

While JavaScriptKit is a great option for occasional interactions with JavaScript, sometimes you need to inject arbitrary scripts or styles, which can be done through direct DOM access:

import JavaScriptKit

let document = JSObject.global.document
let script = document.createElement("script")
script.setAttribute("src", "https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js")
document.head.appendChild(script)

_ = document.head.insertAdjacentHTML("beforeend", #"""
<link
  rel="stylesheet"
  href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
"""#)

This way both Semantic UI styles and moment.js localized date formatting (or any arbitrary style/script/font added that way) are available in your app.

Fiber renderers

A new reconciler modeled after React's Fiber reconciler is optionally available. It can provide faster updates and allow for larger View hierarchies. It also includes layout steps that can match SwiftUI layouts closer than CSS approximations.

You can specify which reconciler to use in your App's configuration:

struct CounterApp: App {
  static let _configuration: _AppConfiguration = .init(
    // Specify `useDynamicLayout` to enable the layout steps in place of CSS approximations.
    reconciler: .fiber(useDynamicLayout: true)
  )

  var body: some Scene {
    WindowGroup("Counter Demo") {
      Counter(count: 5, limit: 15)
    }
  }
}

Note: Not all Views and ViewModifiers are supported by Fiber renderers yet.

Requirements

For app developers

  • macOS 11 and Xcode 13.2 or later when using VS Code. macOS 12 and Xcode 13.3 or later are recommended if you'd like to use Xcode for auto-completion, or when developing multi-platform apps that target WebAssembly and macOS at the same time.
  • Swift 5.6 or later and Ubuntu 18.04/20.04 if you'd like to use Linux. Other Linux distributions are currently not supported.
  • carton 0.15.x (carton is our build tool, see the "Getting started" section for installation steps)

For users of apps depending on Tokamak

Any recent browser that supports WebAssembly and required JavaScript features should work, which currently includes:

  • Edge 84+
  • Firefox 79+
  • Chrome 84+
  • Desktop Safari 14.1+
  • Mobile Safari 14.8+

If you need to support older browser versions, you'll have to build with JAVASCRIPTKIT_WITHOUT_WEAKREFS flag, passing -Xswiftc -DJAVASCRIPTKIT_WITHOUT_WEAKREFS flags when compiling. This should lower browser requirements to these versions:

  • Edge 16+
  • Firefox 61+
  • Chrome 66+
  • (Mobile) Safari 12+

Not all of these versions are tested on regular basis though, compatibility reports are very welcome!

Getting started

Tokamak relies on carton as a primary build tool. As a part of these steps you'll install carton via Homebrew on macOS (unfortunately you'll have to build it manually on Linux). Assuming you already have Homebrew installed, you can create a new Tokamak app by following these steps:

Install carton:

brew install swiftwasm/tap/carton

If you had carton installed before this, make sure you have version 0.15.0 or greater:

carton --version

Create a directory for your project and make it current:

mkdir TokamakApp && cd TokamakApp

Initialize the project from a template with carton:

carton init --template tokamak

Build the project and start the development server, carton dev can be kept running during development:

carton dev

Open http://127.0.0.1:8080/ in your browser to see the app running. You can edit the app source code in your favorite editor and save it, carton will immediately rebuild the app and reload all browser tabs that have the app open.

You can also clone this repository and run carton dev --product TokamakDemo in its root directory. This will build the demo app that shows almost all of the currently implemented APIs.

If you have any questions, pleaes check out the FAQ document, and/or join the #tokamak channel on the SwiftWasm Discord server.

Security

By default, the DOM renderer will escape HTML control characters in Text views. If you wish to override this functionality, you can use the _domTextSanitizer modifier:

Text("<font color='red'>Unsanitized Text</font>")
  ._domTextSanitizer(Sanitizers.HTML.insecure)

You can also use custom sanitizers; the argument to _domTextSanitizer is simply a String -> String closure. If _domTextSanitizer is applied to a non-Text view, it will apply to all Text in subviews, unless overridden.

If you use user-generated or otherwise unsafe strings elsewhere, make sure to properly sanitize them yourself.

Troubleshooting

unable to find utility "xctest" error when building

This error can only happen on macOS, so make sure you have Xcode installed as listed in the requirements. If you do have Xcode installed but still get the error, please refer to this StackOverflow answer.

Syntax highlighting and autocomplete don't work in Xcode

Open Package.swift of your project that depends on Tokamak with Xcode and build it for macOS. As Xcode currently doesn't support cross-compilation for non-Apple platforms, your project can't be indexed if it doesn't build for macOS, even if it isn't fully function on macOS when running. If you need to exclude some WebAssembly-specific code in your own app that doesn't compile on macOS, you can rely on #if os(WASI) compiler directives.

All relevant modules of Tokamak (including TokamakDOM) should compile on macOS. You may see issues with TokamakShim on macOS Catalina, where relevant SwiftUI APIs aren't supported, but replacing import TokamakShim with import TokamakDOM should resolve the issue until you're able to update to macOS Big Sur.

If you stumble upon code in Tokamak that doesn't build on macOS and prevents syntax highlighting or autocomplete from working in Xcode, please report it as a bug.

Syntax highlighting and autocomplete don't work in VSCode

Make sure you have the SourceKit LSP extension installed. If you don't trust this unofficial release, please follow the manual building and installation guide. Apple currently doesn't provide an official build of the extension on the VSCode Marketplace unfortunately.

Contributing

All contributions, no matter how small, are very welcome. You don't have to be a web developer or a SwiftUI expert to meaningfully contribute. In fact, by checking out how some of the simplest views are implemented in Tokamak you may learn more how SwiftUI may work under the hood.

Updating our documentation and taking on the starter bugs is also appreciated. Don't forget to join our Discord server to get in touch with the maintainers and other users. See CONTRIBUTING.md for more details.

Code of Conduct

This project adheres to the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to conduct@tokamak.dev.

Sponsorship

If this library saved you any amount of time or money, please consider sponsoring the work of its maintainers on their sponsorship pages: @carson-katri, @kateinoigakukun, and @MaxDesiatov. While some of the sponsorship tiers give you priority support or even consulting time, any amount is appreciated and helps in maintaining the project.

Maintainers

In alphabetical order: Carson Katri, Ezra Berch, Jed Fox, Morten Bek Ditlevsen, Yuta Saito.

Acknowledgments

  • Thanks to the Swift community for building one of the best programming languages available!
  • Thanks to everyone who developed React with its reconciler/renderer architecture that inspired Tokamak in the first place.
  • Thanks to the designers of the SwiftUI API who showed us how to write UI apps in Swift declaratively (arguably even in a better way than React did).
  • Thanks to SwiftWebUI for reverse-engineering some of the bits of SwiftUI and kickstarting the front-end Swift ecosystem for the web.
  • Thanks to Render, ReSwift, Katana UI and Komponents for inspiration!

SwiftUI is a trademark owned by Apple Inc. Software maintained as a part of the Tokamak project is not affiliated with Apple Inc.

Download Details:

Author: TokamakUI
Source Code: https://github.com/TokamakUI/Tokamak 
License: Apache-2.0 license

#swift #dom #webassembly 

SwiftUI-compatible Framework for Building Browser App with WebAssembly
Reid  Rohan

Reid Rohan

1665075840

XMLDOM: A PURE JS W3C Standard Based DOMParser & XMLSerializer

XMLDOM

A JavaScript implementation of W3C DOM for Node.js, Rhino and the browser. Fully compatible with W3C DOM level2; and some compatible with level3. Supports DOMParser and XMLSerializer interface such as in browser.

Install:

npm install xmldom

Example:

var DOMParser = require('xmldom').DOMParser;
var doc = new DOMParser().parseFromString(
    '<xml xmlns="a" xmlns:c="./lite">\n'+
        '\t<child>test</child>\n'+
        '\t<child></child>\n'+
        '\t<child/>\n'+
    '</xml>'
    ,'text/xml');
doc.documentElement.setAttribute('x','y');
doc.documentElement.setAttributeNS('./lite','c:x','y2');
var nsAttr = doc.documentElement.getAttributeNS('./lite','x')
console.info(nsAttr)
console.info(doc)

API Reference

DOMParser:

parseFromString(xmlsource,mimeType)
  • options extension by xmldom(not BOM standard!!)
//added the options argument
new DOMParser(options)

//errorHandler is supported
new DOMParser({
	/**
	 * locator is always need for error position info
	 */
	locator:{},
	/**
	 * you can override the errorHandler for xml parser
	 * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
	 */
	errorHandler:{warning:function(w){console.warn(w)},error:callback,fatalError:callback}
	//only callback model
	//errorHandler:function(level,msg){console.log(level,msg)}
})

XMLSerializer

serializeToString(node)

DOM level2 method and attribute:

Node

 attribute:
 	nodeValue|prefix
 readonly attribute:
 	nodeName|nodeType|parentNode|childNodes|firstChild|lastChild|previousSibling|nextSibling|attributes|ownerDocument|namespaceURI|localName
 method:	
 	insertBefore(newChild, refChild)
 	replaceChild(newChild, oldChild)
 	removeChild(oldChild)
 	appendChild(newChild)
 	hasChildNodes()
 	cloneNode(deep)
 	normalize()
 	isSupported(feature, version)
 	hasAttributes()

DOMImplementation

 method:
 	hasFeature(feature, version)
 	createDocumentType(qualifiedName, publicId, systemId)
 	createDocument(namespaceURI, qualifiedName, doctype)

Document : Node

 readonly attribute:
 	doctype|implementation|documentElement
 method:
 	createElement(tagName)
 	createDocumentFragment()
 	createTextNode(data)
 	createComment(data)
 	createCDATASection(data)
 	createProcessingInstruction(target, data)
 	createAttribute(name)
 	createEntityReference(name)
 	getElementsByTagName(tagname)
 	importNode(importedNode, deep)
 	createElementNS(namespaceURI, qualifiedName)
 	createAttributeNS(namespaceURI, qualifiedName)
 	getElementsByTagNameNS(namespaceURI, localName)
 	getElementById(elementId)

DocumentFragment : Node

Element : Node

 readonly attribute:
 	tagName
 method:
 	getAttribute(name)
 	setAttribute(name, value)
 	removeAttribute(name)
 	getAttributeNode(name)
 	setAttributeNode(newAttr)
 	removeAttributeNode(oldAttr)
 	getElementsByTagName(name)
 	getAttributeNS(namespaceURI, localName)
 	setAttributeNS(namespaceURI, qualifiedName, value)
 	removeAttributeNS(namespaceURI, localName)
 	getAttributeNodeNS(namespaceURI, localName)
 	setAttributeNodeNS(newAttr)
 	getElementsByTagNameNS(namespaceURI, localName)
 	hasAttribute(name)
 	hasAttributeNS(namespaceURI, localName)

Attr : Node

 attribute:
 	value
 readonly attribute:
 	name|specified|ownerElement

NodeList

 readonly attribute:
 	length
 method:
 	item(index)

NamedNodeMap

 readonly attribute:
 	length
 method:
 	getNamedItem(name)
 	setNamedItem(arg)
 	removeNamedItem(name)
 	item(index)
 	getNamedItemNS(namespaceURI, localName)
 	setNamedItemNS(arg)
 	removeNamedItemNS(namespaceURI, localName)

CharacterData : Node

 method:
 	substringData(offset, count)
 	appendData(arg)
 	insertData(offset, arg)
 	deleteData(offset, count)
 	replaceData(offset, count, arg)

Text : CharacterData

 method:
 	splitText(offset)

CDATASection

Comment : CharacterData

DocumentType

 readonly attribute:
 	name|entities|notations|publicId|systemId|internalSubset

Notation : Node

 readonly attribute:
 	publicId|systemId

Entity : Node

 readonly attribute:
 	publicId|systemId|notationName

EntityReference : Node

ProcessingInstruction : Node

 attribute:
 	data
 readonly attribute:
 	target

DOM level 3 support:

Node

 attribute:
 	textContent
 method:
 	isDefaultNamespace(namespaceURI){
 	lookupNamespaceURI(prefix)

DOM extension by xmldom

[Node] Source position extension;

 attribute:
 	//Numbered starting from '1'
 	lineNumber
 	//Numbered starting from '1'
 	columnNumber

Download Details:

Author: jindw
Source Code: https://github.com/jindw/xmldom 
License: View license

#javascript #xml #dom 

XMLDOM: A PURE JS W3C Standard Based DOMParser & XMLSerializer

Patchwork.jl: Virtual DOM for Julia

Patchwork

A library for representing browser DOM in Julia. It supports element creation, diff computation and browser-side patching.

Setup

From the REPL, run

Pkg.add("Patchwork")

Creating Elements

The Elem constructor can be used to create an element.

# E.g.
using Patchwork

Elem(:h1, "Hello, World!")

creates an h1 heading element equivalent to the HTML <h1>Hello, World!</h1>

You can attach any DOM property (e.g. className, style, height, width) that you would like the DOM node to have by passing it as a keyword argument to Elem

# E.g.
Elem(:h1, "Hello, World!", className="welcome", style=[:color => :white, :backgroundColor => :black])

This creates a h1 with white text on a black background.

You can of course nest elements inside another

Elem(:div, [
    Elem(:h1, "Hello, World!"),
    Elem(:p, "How are you doing today?")])

Elem objects are immutable children(::Elem) returns the children of the element as a persistent vector properties(::Elem) returns the dictionary of its properties. There are some infix operators defined for Elem.

The & operator can set attributes

# E.g.
div_with_class = Elem(:div, "This div's class can change") & [:className => "shiny"]

The << operator can append an element to the end of another.

h1_and_p = Elem(:div, Elem(:h1, "Hello, World!")) << Elem(:p, "How are you doing today?")

SVG graphics are DOM nodes too, and hence can be created in Patchwork.

    Elem(:svg, Elem(:circle, cx=250, cy=250, r=100, fill="orange"),
         width=500, height=500)

draws a circle.

If you are using IJulia, you can use the Interact.jl's @manipulate statement to draw a circle whose position, radius and color can be changed:

using Interact, Patchwork
@manipulate for r=1:100, cx = 1:500, cy=1:400, color=["orange", "green", "blue"]
    Elem(:svg, Elem(:circle, cx=cx, cy=cy, r=r, fill=color),
         width=500, height=500)
end

Diff computation

The diff function computes the difference between two elements.

# E.g.
patch = diff(left::Elem, right::Elem)

Returns a "patch". A patch is a Dict which maps node indices to a list of patches on that node. The node index is a number representing the position of the node in a depth-first ordering starting at the root node (here left), whose index is 0.

Elems are based on immutable datastructures. & and << operations return new Elems, which may share structure with the operands. The more structure two nodes share, the faster the diffing.

For example, if you have a big Elem, say averybigelem, the running time of the following diff call

diff(averybigelem, averybigelem & [:className => "shiny"])

will not depend on the size and complexity of averybigelem because diffing gets short-circuited since left.children === right.children. It will probably be helpful to keep this in mind while building something with Patchwork.

JavaScript setup and patching

Patchwork has a javascript "runtime" in runtime/build.js that needs to be included into a page where you would like to display Patchwork nodes.

<script src="/path/to/build.js"></script>

This is automatically done for you if you are using Patchwork from IJulia.

Patchwork defines the writemime(io::IO, ::MIME"text/html", ::Elem) method which can use JavaScript to display nodes and/or apply patches to nodes that are already displayed.

At a lower level, the runtime exposes the window.Patchwork object, which can be used to render nodes from their JSON representations and also apply patches.

// E.g.
node = new Patchwork.Node(mountId, elemJSON)

this renders the node represented by elemJSON and appends it to a DOM element with id mountId.

Patchwork.Node instances have an applyPatch method which can be used to patch the node.

// E.g.
node.applyPatch(patchJSON)

With Compose and Gadfly

If Patchwork is installed, interactive plots or Compose graphics automatically use Patchwork to efficiently render them into SVG Virtual DOM. Any updates to the plot get turned into patches, sent over to the browser and applied to the plot.

Usage in IJulia

When you load Patchwork in IJulia, the runtime is setup automatically for you. If the result of executing a cell is an Elem object, it gets rendered in the cell's output area. display(::Elem) will work too.

When used with Reactive (or Interact), any Signal{Elem} values (see Reactive.Signal) get displayed with its initial value first. Subsequent updates are sent as patches and applied at the front-end.

Development

You will need a recent nodejs and npm installed to hack on the JavaScript part of this package.

To build the JS files run the following from runtime/ directory:

npm install .
npm install -g browserify
npm install -g uglifyjs
make

Thanks

  • This package is largely based on Matt-Esch's excellent virtual-dom and vtree JavaScript modules. Patchwork's JS makes use of virtual-dom and virtual-hyperscript by Raynos.
  • Thanks to Evan Czaplicki for creating Elm which inspired me to take the FRP road.

Download Details:

Author: shashi
Source Code: https://github.com/shashi/Patchwork.jl 
License: View license

#julia #dom 

Patchwork.jl: Virtual DOM for Julia
Lawrence  Lesch

Lawrence Lesch

1662107520

Superdom: Better and Simpler ES6 DOM Manipulation

Superdom

You have dom. It has all the DOM virtually within it. Use that power:

// Fetch all the page links
let links = dom.a.href;

// Links open in a new tab
dom.a.target = '_blank';

Only for modern browsers

Getting started

Simply use the CDN via unpkg.com:

<script src="https://unpkg.com/superdom@1"></script>

Or use npm or bower:

npm|bower install superdom --save

Select

It always returns an array with the matched elements. Get all the elements that match the selector:

// Simple element selector into an array
let allLinks = dom.a;

// Loop straight on the selection
dom.a.forEach(link => { ... });

// Combined selector
let importantLinks = dom['a.important'];

There are also some predetermined elements, such as id, class and attr:

// Select HTML Elements by id:
let main = dom.id.main;

// by class:
let buttons = dom.class.button;

// or by attribute:
let targeted = dom.attr.target;
let targeted = dom.attr['target="_blank"'];

Generate

Use it as a function or a tagged template literal to generate DOM fragments:

// Not a typo; tagged template literals
let link = dom`<a href="https://google.com/">Google</a>`;

// It is the same as
let link = dom('<a href="https://google.com/">Google</a>');

Delete elements

Delete a piece of the DOM

// Delete all of the elements with the class .google
delete dom.class.google;   // Is this an ad-block rule?

Attributes

You can easily manipulate attributes right from the dom node. There are some aliases that share the syntax of the attributes such as html and text (aliases for innerHTML and textContent). There are others that travel through the dom such as parent (alias for parentNode) and children. Finally, class behaves differently as explained below.

Get attributes

The fetching will always return an array with the element for each of the matched nodes (or undefined if not there):

// Retrieve all the urls from the page
let urls = dom.a.href;     // #attr-list
  // ['https://google.com', 'https://facebook.com/', ...]

// Get an array of the h2 contents (alias of innerHTML)
let h2s = dom.h2.html;     // #attr-alias
  // ['Level 2 header', 'Another level 2 header', ...]

// Get whether any of the attributes has the value "_blank"
let hasBlank = dom.class.cta.target._blank;    // #attr-value
  // true/false

You also use these:

  • html (alias of innerHTML): retrieve a list of the htmls
  • text (alias of textContent): retrieve a list of the htmls
  • parent (alias of parentNode): travel up one level
  • children: travel down one level

Set attributes

// Set target="_blank" to all links
dom.a.target = '_blank';     // #attr-set
dom.class.tableofcontents.html = `
  <ul class="tableofcontents">
    ${dom.h2.map(h2 => `
      <li>
        <a href="#${h2.id}">
          ${h2.innerHTML}
        </a>
      </li>
    `).join('')}
  </ul>
`;

Remove an attribute

To delete an attribute use the delete keyword:

// Remove all urls from the page
delete dom.a.href;

// Remove all ids
delete dom.a.id;

Classes

It provides an easy way to manipulate the classes.

Get classes

To retrieve whether a particular class is present or not:

// Get an array with true/false for a single class
let isTest = dom.a.class.test;     // #class-one

For a general method to retrieve all classes you can do:

// Get a list of the classes of each matched element
let arrays = dom.a.class;     // #class-arrays
  // [['important'], ['button', 'cta'], ...]

// If you want a plain list with all of the classes:
let flatten = dom.a.class._flat;     // #class-flat
  // ['important', 'button', 'cta', ...]

// And if you just want an string with space-separated classes:
let text = dom.a.class._text;     // #class-text
  // 'important button cta ...'

Add a class

// Add the class 'test' (different ways)
dom.a.class.test = true;    // #class-make-true
dom.a.class = 'test';       // #class-push

Remove a class

// Remove the class 'test'
dom.a.class.test = false;    // #class-make-false

Manipulate

Did we say it returns a simple array?

dom.a.forEach(link => link.innerHTML = 'I am a link');

But what an interesting array it is; indeed we are also proxy'ing it so you can manipulate its sub-elements straight from the selector:

// Replace all of the link's html with 'I am a link'
dom.a.html = 'I am a link';

Of course we might want to manipulate them dynamically depending on the current value. Just pass it a function:

// Append ' ^_^' to all of the links in the page
dom.a.html = html => html + ' ^_^';

// Same as this:
dom.a.forEach(link => link.innerHTML = link.innerHTML + ' ^_^');

Note: this won't work dom.a.html += ' ^_^'; for more than 1 match (for reasons)

Or get into genetics to manipulate the attributes:

dom.a.attr.target = '_blank';

// Only to external sites:
let isOwnPage = el => /^https?\:\/\/mypage\.com/.test(el.getAttribute('href'));
dom.a.attr.target = (prev, i, element) => isOwnPage(element) ? '' : '_blank';

Events

You can also handle and trigger events:

// Handle click events for all <a>
dom.a.on.click = e => ...;

// Trigger click event for all <a>
dom.a.trigger.click;

Testing

We are using Jest as a Grunt task for testing. Install Jest and run in the terminal:

grunt watch

Download Details:

Author: franciscop
Source Code: https://github.com/franciscop/superdom 
License: MIT license

#javascript #es6 #dom 

Superdom: Better and Simpler ES6 DOM Manipulation
Dexter  Goodwin

Dexter Goodwin

1661247720

Neo: The Application Worker Driven Frontend Framework

Welcome to neo.mjs!

neo.mjs enables you to create scalable & high performant Apps using more than just one CPU. No need to take care of a workers setup, and the cross channel communication on your own.

Version 4 release announcement

1. Slack Channel for questions & feedback

Join our community: Slack Channel Invite Link

2. Scalable frontend architectures

Most frontends today still look like this. Everything happens inside the main thread (browser window), leading to a poor rendering performance. The business logic happens inside main as well, which can slow down DOM updates and animations. The worst case would be a complete UI freeze.

To solve this performance problem, it is not enough to just move expensive tasks into a worker. Instead, an application worker needs to be the main actor. neo.mjs offers two different setups which follow the exact same API. You can switch between dedicated and shared workers at any point.

The dedicated workers setup uses 3-6 threads (CPUs). Most parts of the frameworks as well as your apps and components live within the app worker. Main threads are as small and idle as possible (42KB) plus optional main thread addons.

In case you want to e.g. create a web based IDE or a multi window banking / trading app, the shared worker setup using 5+ threads (CPUs) is the perfect solution.

All main threads share the same data, resulting in less API calls. You can move entire component trees across windows, while even keeping the same JS instances. Cross window state management, cross window drag&drop and cross window delta CSS updates are available.

3. Multi Browser Window COVID19 IN NUMBERS Demo App

The most compelling way to introduce a new framework might simply be to show what you can do with it.

Blog post: Expanding Single Page Apps into multiple Browser Windows

Live Demo: COIN App (Multi Window)
Chrome (v83+), Edge, Firefox (Safari does not support SharedWorkers yet).
Desktop only.

You can find the code of the multi window covid app here.

4. COVID19 IN NUMBERS Demo App

Live Demo: COIN App dist/production
Desktop only => support for mobile devices is on the roadmap.

You can find the code of the covid app here.

5. Short overview of the concept & design goals

 What if ...Benefit
1.... a framework & all the apps you build are running inside a separate thread (web worker)?You get extreme Performance
2.... the main thread would be mostly idle, only applying the real dom manipulations, so there are no background tasks slowing it down?You get extreme UI responsiveness
3.... a framework was fully built on top of ES8, but can run inside multiple workers without any Javascript builds?Your development speed will increase
4.... you don’t need source-maps to debug your code, since you do get the real code 1:1?You get a smoother Debugging Experience
5.... you don’t have to use string based pseudo XML templates ever again?You get unreached simplicity, no more scoping nightmares
6.... you don’t have to use any sort of templates at all, ever again?You gain full control!
7.... you can use persistent JSON structures instead?You gain more simplicity
8.... there is a custom virtual dom engine in place, which is so fast, that it will change your mind about the performance of web based user interfaces?You get extreme performance
9.... the ES8 class system gets enhanced with a custom config system, making it easier to extend and work with config driven design patterns?Extensibility, a robust base for solid UI architectures
10.... your user interfaces can truly scale?You get extreme Performance

6. Want to learn more?

neo.mjs Concepts

7. Online Examples

You can find a full list of (desktop based) online examples here:
Online Examples

You can pick between the 3 modes (development, dist/development, dist/production) for each one.

8. Online Docs

The Online Docs are also included inside the Online Examples.

dist/production does not support lazy loading the examples yet, but works in every browser:
Online Docs (dist/production)

The development mode only works in Chrome and Safari Technology Preview, but does lazy load the example apps:
Online Docs (dev mode)

Hint: As soon as you create your own apps, you want to use the docs app locally,
since this will include documentation views for your own apps.

9. Command-Line Interface

You can run several build programs inside your terminal.
Please take a look at the Command-Line Interface Guide.

10. Ready to get started?

There are 3 different ways on how you can get the basics running locally.
Please take a look at the Getting Started Guide.

Here is an in depth tutorial on how to build your first neo.mjs app:
https://itnext.io/define-a-web-4-0-app-to-be-multi-threaded-9c495c0d0ef9?source=friends_link&sk=4d143ace05f0e9bbe82babd9433cc822 

11. Story & Vision

Although neo.mjs is ready to craft beautiful & blazing fast UIs,
the current state is just a fraction of a bigger picture.

Take a look at the Project Story and Vision.

12. neo.mjs is in need for more contributors!

Another way to fasten up the neo.mjs development speed is to actively jump in.
As the shiny "PRs welcome" badge suggests: open source is intended to be improved by anyone who is up for the challenge.

You can also write a guide in case you learned something new while using neo.mjs or just help to get more eyes on this project.

Either way, here are more infos: Contributing

13. neo.mjs is in need for sponsors!

neo.mjs is an MIT-licensed open source project with an ongoing development.
So far the development was made possible with burning my (tobiu's) personal savings.
 

This is obviously not sustainable. To enable me keep pushing like this, please support it.
The benefit of doing so is getting results delivered faster.

Sponsor tobiu

More infos: Sponsors & Backers

14. Jobs

Accenture is hiring multiple neo.mjs developers for the new Cloud Technology Studio in Kaiserslauern (Germany): Senior neo.mjs Frontend Developer /Architect (all genders)

These full-time roles are based on German contracts, so they require living in (or relocating to) Germany. Ping us on LinkedIn or Slack for details.

Logo contributed by Torsten Dinkheller.

Build with ❤️ in Germany.

Copyright (c) 2015 - today, Tobias Uhlig & Rich Waters

Download Details:

Author: Neomjs
Source Code: https://github.com/neomjs/neo 
License: MIT license

#javascript #virtual #dom #json #frontend 

Neo: The Application Worker Driven Frontend Framework
Tech2 etc

Tech2 etc

1660741784

React Navbar Tutorial - Responsive Navbar React JS

Advance React JS Responsive Navbar

Over the years, navigation bars, or navbars, have become a staple feature in building websites. They really come in handy for navigating across a website.

We will Create react navbar using advanced react js methods. In our previous tutorial, we have created a responsive navbar using basic react js. But in this tutorial we are going to use advance functionalities for creating this navbar using react js.

In this tutorial, we’ll go over the basics of building navbars in React. We’ll build a navbar that’s fixed to the top of the page, and the user will be able to switch between webpages like you can on a dashboard, for instance. We’ll then put all our newfound skills into practice by building a live sample app.

Our sample app is an animal gallery that we’ll use to view some pictures of different types of animals after we click the animal’s name on the navigation bar.

Installation

Let’s get right into the code. To create a React app, make sure you have Node.js installed on your computer. If you haven’t built a React app before, you can check to see if you have Node.js installed by typing the following into your terminal:

node -v

If not, just go to the Node.js website to download the latest version.

Once that’s done, we can get started with our React app by running this command:

npx create-react-app nav-bar                                             

Then, we navigate into our project folder on the terminal:

cd nav-bar

Setting up the React Router library

Using the React Router library in our application allows us to navigate between different pages or components in React, and actually makes these changes to the URL of each page or component. In fact, it can also handle more complex functionalities, like passing data between pages through queries and nested routes — but that’s beyond the scope of this article.

For this example, we’ll only need to install the React Router library to help us switch views of the animals in our app when we click on the nav names on the links.

npm install react-router-dom

Check out the tutorial for complete project.

Resources:

Code Sandbox: https://codesandbox.io/

Level 1(Previous Tutorial): https://youtu.be/23BHwAFIZmk

Source Code1: https://www.buymeacoffee.com/tech2etc/e/85299

Source Code2: https://ko-fi.com/s/7f02c9c3fd

Template & Setup(VS Code): https://github.com/tech2etc/React_Navbar_2

 

#react-native #react #nestjs #dom #htmlcss #web-development #dev 

React Navbar Tutorial - Responsive Navbar React JS
Anne  de Morel

Anne de Morel

1660062600

Différence Entre Le Nœud DOM Et L'élément ?

Le modèle d'objet de document (DOM) est une interface qui traite le document HTML ou XML comme une structure arborescente, où chaque nœud est un objet du document. DOM fournit également un ensemble de méthodes pour interroger l'arbre, modifier la structure, le style.

DOM utilise également le terme element : qui est assez similaire à un nœud. Alors, quelle est la différence entre un nœud DOM et un élément ? Découvrons-le!

1. Nœud DOM

La clé pour comprendre la différence entre un nœud et un élément est de comprendre ce qu'est un nœud.

D'un point de vue supérieur, un document DOM consiste en une hiérarchie de nœuds. Chaque nœud peut avoir un parent et/ou des enfants.

Regardons le document HTML suivant :

<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <!-- Page Body -->
    <h2>My Page</h2>
    <p id="content">Thank you for visiting my web page!</p>
  </body>
</html>

Le document contient la hiérarchie de nœuds suivante :

Hiérarchie des nœuds DOM

<html>est un nœud dans l'arborescence du document. Il a 2 enfants : <head>et les <body>nœuds.

<body>est également un nœud ayant 3 enfants : un commentaire <!-- Page Body -->, un titre <h2>et un paragraphe <p>. Le parent du <body>nœud est <html>node.

Les balises dans le document HTML représentent un nœud, ce qui est intéressant, c'est que le texte normal est également un nœud. Le nœud de paragraphe <p>a 1 enfant : le nœud de texte "Thank you for visiting my web page!".

1.2 Types de nœuds

Comment pouvez-vous distinguer ces différents types de nœuds ? La réponse se trouve dans l' interface DOM NodeNode.nodeType , en particulier dans la propriété.

Node.nodeTypepeut avoir l'une des valeurs suivantes qui représente le type du nœud :

Node.ELEMENT_NODE
Node.ATTRIBUTE_NODE
Node.TEXT_NODE
Node.CDATA_SECTION_NODE
Node.PROCESSING_INSTRUCTION_NODE
Node.COMMENT_NODE
Node.DOCUMENT_NODE
Node.DOCUMENT_TYPE_NODE
Node.DOCUMENT_FRAGMENT_NODE
Node.NOTATION_NODE

Les constantes indiquent de manière significative le type de nœud : par exemple Node.ELEMENT_NODEreprésente un nœud d'élément, Node.TEXT_NODEreprésente un nœud de texte, Node.DOCUMENT_NODEle nœud de document, etc.

Par exemple, sélectionnons le nœud de paragraphe et examinons sa nodeTypepropriété :

const paragraph = document.querySelector('p');
paragraph.nodeType === Node.ELEMENT_NODE; // => true

Comme prévu paragraph.nodeTypea la valeur Node.ELEMENT_NODE, indiquant que le paragraphe est un élément.

Le paragraphe contient également un nœud de texte :

const paragraph = document.querySelector('p');
const firstChild = paragraph.childNodes[0];
firstChild.nodeType === Node.TEXT_NODE; // => true

Il existe un type de nœud qui représente l'intégralité de l'arborescence des nœuds du document —Node.DOCUMENT_NODE :

document.nodeType === Node.DOCUMENT_NODE; // => true

2. Élément DOM

Après avoir bien compris ce qu'est un nœud DOM, il est maintenant temps de différencier le nœud et l'élément DOM.

Si vous obtenez bien le terme de nœud , alors la réponse est évidente : un élément est un nœud d'un type spécifique — élément ( Node.ELEMENT_NODE). Avec des types tels que document, commentaire, texte, etc.

En termes simples, un élément est un nœud écrit à l'aide d'une balise dans le document HTML. <html>, <head>, <title>, <body>, <h2>, <p>sont tous des éléments car ils sont représentés par des balises.

Le type de document, le commentaire, les nœuds de texte ne sont pas des éléments car ils ne sont pas écrits avec des balises :

 <!DOCTYPE html>
<html>
  <body>
    <!-- Page Body -->
    <p>
      Thank you for visiting my web page!
    </p>
  </body>
</html>

Nodeest le constructeur d'un nœud et HTMLElementest le constructeur d'un élément dans JavaScript DOM. Un paragraphe, étant un nœud et aussi un élément, est une instance à la fois de Nodeet HTMLElement:

const paragraph = document.querySelector('p');
paragraph instanceof Node;        // => true
paragraph instanceof HTMLElement; // => true

Pour simplifier, un élément est un sous-type d'un nœud de la même manière qu'un chat est un sous-type d'un animal.

3. Propriétés DOM : nœuds et éléments

En plus de différencier les nœuds des éléments, vous devez également distinguer les propriétés DOM qui contiennent spécifiquement uniquement des nœuds ou uniquement des éléments.

Les propriétés de Nodetype suivantes évaluent un nœud ou une collection de nœuds ( NodeList) :

node.parentNode; // Node or null
node.firstChild; // Node or null
node.lastChild;  // Node or null
node.childNodes; // NodeList

Cependant, les propriétés suivantes sont des éléments ou une collection d'éléments ( HTMLCollection) :

node.parentElement; // HTMLElement or null
node.children;      // HTMLCollection

Puisque les deux node.childNodeset node.childrenrenvoient une liste d'enfants, pourquoi avoir ces deux propriétés ? Bonne question!

Considérez l'élément de paragraphe suivant contenant du texte :

<p>
  <b>Thank you</b> for visiting my web page!
</p>

Ouvrez la démo , puis examinez childNodesles childrenpropriétés du nœud parapgraph :

const paragraph = document.querySelector('p');
paragraph.childNodes; // NodeList:       [HTMLElement, Text]
paragraph.children;   // HTMLCollection: [HTMLElement]

paragraph.childNodescollection contient 2 nœuds : l'élément bold <b>Thank you</b>, ainsi que le nœud text for visiting my web page!.

Cependant, paragraph.childrenla collection ne contient qu'un seul élément : l'élément bold <b>Thank you</b>.

Parce paragraph.childrenqu'il ne contient que des éléments, le nœud de texte n'a pas été inclus ici car son type est texte ( Node.TEXT_NODE) et non un élément ( Node.ELEMENT_NODE).

Avoir à la fois node.childNodeset node.childrenvous permet de choisir la collection d'enfants à laquelle vous souhaitez accéder : tous les nœuds enfants ou uniquement les enfants étant des éléments.

4. Résumé

Un document DOM est une collection hiérarchique de nœuds. Chaque nœud peut avoir un parent et/ou des enfants.

Comprendre la différence entre un nœud DOM et un élément est facile si vous comprenez ce qu'est un nœud.

Les nœuds ont des types, le type d'élément étant l'un d'entre eux. L'élément est représenté par une balise dans le document HTML.

Source : https://dmitripavlutin.com/dom-node-element/

#dom  #nodejs 

Différence Entre Le Nœud DOM Et L'élément ?

DOM ノードと要素の違いは?

ドキュメント オブジェクト モデル (DOM) は、HTML または XML ドキュメントをツリー構造として扱うインターフェイスであり、各ノードはドキュメントのオブジェクトです。DOM は、ツリーを照会したり、構造やスタイルを変更したりする一連のメソッドも提供します。

DOM は要素: という用語も使用しますが、これはノードによく似ています。では、DOM ノードと要素の違いは何でしょうか? 確認してみましょう!

1. DOM ノード

ノードと要素の違いを理解する鍵は、ノードとは何かを理解することです。

高い視点から見ると、DOM ドキュメントはノードの階層で構成されます。各ノードは、親および/または子を持つことができます。

次の HTML ドキュメントを見てみましょう。

<!DOCTYPE html>
<html>
  <head>
    <title>My Page</title>
  </head>
  <body>
    <!-- Page Body -->
    <h2>My Page</h2>
    <p id="content">Thank you for visiting my web page!</p>
  </body>
</html>

ドキュメントには、次のノード階層が含まれています。

DOM ノードの階層

<html>ドキュメント ツリーのノードです。これには 2 つの子があります:<head>および<body>ノー​​ドです。

<body><!-- Page Body -->また、コメント、見出し<h2>、および段落の 3 つの子を持つノードでもあります<p>。ノードの親<body><html>ノードです。

HTML ドキュメントのタグはノードを表します。興味深いのは、通常のテキストもノードであるということです。段落ノード<p>には、テキスト ノードという 1 つの子があります"Thank you for visiting my web page!"

1.2 ノードの種類

これらの異なるタイプのノードをどのように区別できますか? その答えは DOM Nodeインターフェイス、特にNode.nodeTypeプロパティにあります。

Node.nodeTypeノードのタイプを表す次のいずれかの値を持つことができます。

Node.ELEMENT_NODE
Node.ATTRIBUTE_NODE
Node.TEXT_NODE
Node.CDATA_SECTION_NODE
Node.PROCESSING_INSTRUCTION_NODE
Node.COMMENT_NODE
Node.DOCUMENT_NODE
Node.DOCUMENT_TYPE_NODE
Node.DOCUMENT_FRAGMENT_NODE
Node.NOTATION_NODE

定数は、意味のあるノード タイプを示します。たとえばNode.ELEMENT_NODE、要素ノード、Node.TEXT_NODEテキスト ノード、Node.DOCUMENT_NODEドキュメント ノードなどを表します。

たとえば、段落ノードを選択して、そのnodeTypeプロパティを見てみましょう。

const paragraph = document.querySelector('p');
paragraph.nodeType === Node.ELEMENT_NODE; // => true

予想どおり、段落が要素であることを示すparagraph.nodeType値 を持っています。Node.ELEMENT_NODE

段落にはテキスト ノードも含まれます。

const paragraph = document.querySelector('p');
const firstChild = paragraph.childNodes[0];
firstChild.nodeType === Node.TEXT_NODE; // => true

ノードのドキュメント ツリー全体を表すノード タイプがあります — Node.DOCUMENT_NODE:

document.nodeType === Node.DOCUMENT_NODE; // => true

2.DOM要素

DOM ノードとは何かを十分に理解したら、今度は DOM ノードと要素を区別します。

ノードという用語が理解できれば、答えは明らかです。要素とは、特定のタイプのノード — 要素 ( Node.ELEMENT_NODE) です。ドキュメント、コメント、テキストなどのタイプとともに。

簡単に言えば、要素は HTML ドキュメント内のタグを使用して記述されたノードです。<html><head><title><body>、は、タグで表されるため<h2><p>すべての要素です。

ドキュメント タイプ、コメント、テキスト ノードは、タグで記述されていないため、要素ではありません。

 <!DOCTYPE html>
<html>
  <body>
    <!-- Page Body -->
    <p>
      Thank you for visiting my web page!
    </p>
  </body>
</html>

NodeノードHTMLElementのコンストラクタであり、JavaScript DOM の要素のコンストラクタです。ノードであり要素でもある段落は、 と の両方のインスタンスNodeですHTMLElement

const paragraph = document.querySelector('p');
paragraph instanceof Node;        // => true
paragraph instanceof HTMLElement; // => true

簡単に言うと、猫が動物のサブタイプであるのと同じように、エレメントはノードのサブタイプです。

3. DOM プロパティ: ノードと要素

ノードと要素を区別するだけでなく、明確にノードのみ、または要素のみを含む DOM プロパティも区別する必要があります。

タイプの次のプロパティはNode、ノードまたはノードのコレクション ( NodeList)に評価されます。

node.parentNode; // Node or null
node.firstChild; // Node or null
node.lastChild;  // Node or null
node.childNodes; // NodeList

ただし、次のプロパティは要素または要素のコレクションです ( HTMLCollection)。

node.parentElement; // HTMLElement or null
node.children;      // HTMLCollection

と の両方が子のリストnode.childNodesnode.children返すのに、なぜこれらのプロパティの両方があるのでしょうか? 良い質問!

テキストを含む次の段落要素を考えてみましょう。

<p>
  <b>Thank you</b> for visiting my web page!
</p>

demoを開き、段落ノードchildNodeschildrenプロパティを確認します。

const paragraph = document.querySelector('p');
paragraph.childNodes; // NodeList:       [HTMLElement, Text]
paragraph.children;   // HTMLCollection: [HTMLElement]

paragraph.childNodesコレクションには、太字要素<b>Thank you</b>とテキスト ノードの 2 つのノードが含まれますfor visiting my web page!

ただし、paragraph.childrenコレクションに含まれる項目は 1 つだけです: bold 要素<b>Thank you</b>.

含まれているのは要素のみであるためparagraph.children、テキスト ノードのタイプはテキスト ( Node.TEXT_NODE) であり、要素 ( Node.ELEMENT_NODE) ではないため、ここには含まれていません。

と の両方node.childNodesnode.children使用すると、アクセスしたい子のコレクションを選択できます: すべての子ノードまたは子のみが要素です。

4. まとめ

DOM ドキュメントは、ノードの階層的なコレクションです。各ノードは、親および/または子を持つことができます。

ノードが何であるかを理解していれば、DOM ノードと要素の違いを理解するのは簡単です。

ノードにはタイプがあり、要素タイプはその 1 つです。要素は、HTML ドキュメント内のタグによって表されます。

ソース: https://dmitripavlutin.com/dom-node-element/

#dom #nodejs 

DOM ノードと要素の違いは?