Node PropertiesType, Tag and Contents

Node Properties:Type, Tag and Contents

In this chapter, we are going to take an in-depth look at the DOM nodes in JavaScript. Let’s explore what they are and learn their most common properties. (在本章中,我们将深入了解JavaScript中的DOM节点。让我们探索它们是什么,并了解它们最常见的属性。)

DOM Node Classes

DOM Node Classes (DOM节点类)

Different DOM nodes obtain various properties. For example, an element node that corresponds to tag <a> has link-related properties. The one that corresponds to <input> has input-related properties. Text nodes and element nodes are not the same. However, they have some common properties and methods that form a single hierarchy.

Each of the DOM nodes is a part of the matching built-in class. (每个DOM节点是匹配内置类的一部分。)

EventTarget is the root of the hierarchy and is inherited by Node. Other DOM nodes inherit from it. To get more comprehensive information, please, look at the picture and its explanation below:

So, the classes are as follows:

  • EventTarget: it’s the root “abstract” class. That class objects are never created. So, it serves as a base.

  • Node: another “abstract” class that serves as a base for the nodes of DOM. Node provides the basic tree functionality: parentNode, nextSibling, childNodes, and more. They are considered getters. The Node class objects are never created either. However, concrete node classes inherit from it: Among them are Text ( for text nodes), Element ( for element nodes), or Comment ( for comment nodes).

  • Element a base class for the elements of DOM. It allows element-level navigation (for example, nextElementSibling, children and methods of search, such as getElementsByTagName, querySelector). A browser can support HTML, XML, well as SVG. The element class is a base for more specific classes, such as HTMLElement, SVGElement, and XMLElement. (- DOM元素的基类元素。它允许元素级导航(例如, nextElementSibling、子级和搜索方法,例如getElementsByTagName、querySelector )。浏览器可以支持HTML、XML和SVG。元素类是更具体类的基础,例如HTMLElement、SVGElement和XMLElement。)

  • HTMLElement: the basic class for all the HTMLElement. It is inherited from specific HTML elements that are the following:

HTMLInputElement: it’s the class of <input> elements. HTMLBodyElement: the class of <body> elements. HTMLAnchorElement: the class of <a> elements.

We can continue counting them. Every tag has its class that can provide particular methods and properties. (我们可以继续计算。每个标记都有其可以提供特定方法和属性的类。)

So, the set of properties and methods of a particular node is the result of the inheritance. (因此,特定节点的属性和方法集是继承的结果。)

Let’s check out a case where the DOM object serves as an <input> element. It is related to the HTMLInputElement class.

It will get methods and properties as a superposition of the following:

  • HTMLInputElement - provides input-specific properties. (- HTMLInputElement -提供特定于输入的属性。)

  • HTMLElement - provides HTML element-methods that are used frequently. (- HTMLElement -提供经常使用的HTML元素方法。)

  • Element - offers generic element methods. (- Element -提供通用元素方法。)

  • Node - provides DOM node properties that are common. (-节点-提供常见的DOM节点属性。)

  • EventTarget - provides support for events. (- EventTarget -提供对事件的支持。)

  • Also, it inherits from Object, so hasOwnProperty and other “plain object” methods are available, too. (-此外,它继承自Object ,因此也可以使用OwnProperty和其他“普通对象”方法。)

DOM nodes belong to regular JavaScript objects. The prototype-based classes for inheritance are used by them. It is easy to see through outputting an element using console.dir(elem) in a browser. In the console, it is possible to see HTMLElement.prototype, Element.prototype and more. (DOM节点属于常规JavaScript对象。它们使用基于原型的继承类。在浏览器中使用console.dir (elem)输出元素很容易看到。在控制台中,可以看到HTMLElement.prototype、Element.prototype等。)

Most of the browsers support the following commands: console.dir and console.log. Their arguments are output to the console. These commands do the same for JavaScript objects.

But, they are not the same for the DOM elements. (但是,对于DOM元素,它们并不相同。)

console.dir(elem) demonstrates the element as a DOM object. console.log(elem) demonstrates the element DOM tree. (console.dir (elem)将元素演示为DOM对象。 console.log (elem)演示元素DOM树。)

DOM objects are not described by using JavaScript, but a unique Interface Description Language (IDL). Usually, it’s easy-understandable. (DOM对象不是使用JavaScript描述的,而是使用唯一的接口描述语言(IDL)。通常,这很容易理解。)

All the properties in IDL are prepended by the type. For example, boolean, DOMString , and more. The example looks like this:

// Define HTMLInputElement
// The colon ":" means that the HTMLInputElement inherits from HTMLElement
interface HTMLInputElement: HTMLElement {
 // here go properties and methods of the  <input> elements
 // "DOMString" means the property value is a string
(//"DOMString"表示属性值为字符串)
 attribute DOMString accept;
 attribute DOMString alt;
 attribute DOMString autocomplete;
 attribute DOMString value;
 //the boolean value property (true/false)
(//布尔值属性( true/false ))
 attribute boolean autofocus;
 ...
 // now the method: "void" means that the method does not return value
 void select();
 ...
}

The “nodeType” property

The “nodeType” property (“nodeType”属性)

The nodeType property represents another old way of getting the type of a DOM node. (NodeType属性表示获取DOM节点类型的另一种旧方法。)

It has got a numeric value, as demonstrated below:

  • For element nodes- element.nodeType == 1 (-对于元素节点- element.nodeType = = 1)

  • For text nodes-element.nodeType == 3 (-对于文本nodes-element.nodeType = = 3)

  • For the document object-element.nodeType == 9 (-对于文档object-element.nodeType = = 9)

The specification includes several other values too. (该规范还包括其他几个值。)

Let’s check out an example:

let element = document.body;    
// let's examine what is it?
console.log(element.nodeType); // 1 => element
// and the first child is
console.log(element.firstChild.nodeType); // 3 => text
// for the document object type is 9
console.log( document.nodeType ); // 9

But, you can easily use instanceof and other class-based tests to see the type of the node. Sometimes it can be more straightforward. However, you can only read with no option of changing it. (但是,您可以轻松地使用instanceof和其他基于类的测试来查看节点的类型。有时它可以更直截了当。但是,您只能阅读,不能更改。)

Tag: nodeName and tagName

Tag: nodeName and tagName

You can read the tag of DOM node name from the properties, such as tagName or nodeName. (可以从属性中读取DOM节点名称的标记,如tagName或nodeName。)

Here is an example of using nodeName and tagName:

console.log(document.body.nodeName); // BODY
console.log(document.body.tagName); // BODY

Now, let’s see the differences between these two properties. (现在,让我们来看看这两个属性之间的差异。)

First of all, tagName exists only for the Element nodes. On its turn, the nodeName is for any Node: for elements, it’s equivalent to tagName, and for other types of nodes ( for example, text, comment, and more), it contains a string with the node type.

In brief, tagName is supported by element nodes, and nodeName may say something about the other types of nodes. (简而言之, tagName由元素节点支持, nodeName可能会对其他类型的节点发表一些看法。)

The comparison of tagName and nodeName for the document and comment node will look as follows:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <!-- comment -->
   <script>
     // for comment
(用于注释)
     alert( document.body.firstChild.tagName ); // undefined, not an element
     alert( document.body.firstChild.nodeName ); // #comment      
     // for document
(//FOR DOCUMEN)
     alert( document.tagName ); // undefined, not an element
     alert( document.nodeName ); // #document
   </script>
 </body>
</html>

In case of dealing with elements, you can use both tagName and nodeName. (在处理元素的情况下,可以同时使用tagName和nodeName。)

Generally, the browser has two modes to process documents: HTML and XML. as a rule, HTML mode is enabled for web pages. The XML mode is used when browser gets an XML document with the Content-Type: application/xml+xhtml header.

The tagName and nodeName should always be uppercased in HTML mode. For example, it’s BODY either for <body> or <BoDy>.

For the XML mode, the case is kept “as is”. Anyway, XML is rarely used nowadays. (对于XML模式,大小写保持“原样”。无论如何,现在很少使用XML。)

innerHTML: the contents

innerHTML: the contents

If you want to get the HTML inside the element as a string, the innerHTML property will help you do it. You can modify it as well., and it’s one of the most robust means of changing the page. (如果要将元素中的HTML作为字符串获取, innerHTML属性将帮助您完成此操作。您也可以对其进行修改,这是更改页面最强大的方法之一。)

The example below demonstrates the contents of document.body, completely replacing it:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <p>Paragraph</p>
   <div>div</div>
   <script>
     alert( document.body.innerHTML ); // read the current contents
     document.body.innerHTML = 'The new body!'; // replace it
   </script>
 </body>
</html>

In another example, let’s insert not valid HTML, to see how the browser fixes the errors:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <script>
     document.body.innerHTML = '<b>test'; // forgot to close the tag
     alert( document.body.innerHTML ); // <b>test</b> (fixed)
   </script>
 </body>
</html>

Be careful: “innerHTML+=” will do a full overwrite.

You can append HTML to an element enforcing element.innerHTML+=“more html”, like in the example below:

div.innerHTML += "
<div>Welcome<img src=' '/> !</div>
";
div.innerHTML += "How goes?";

But, please note that you need to do it very carefully as it leads to a full overwrite. (但是,请注意,您需要非常小心地执行此操作,因为它会导致完全覆盖。)

The two lines, demonstrated below, technically do the same:

element.innerHTML += "...";
// is a shorter way to write:
element.innerHTML = element.innerHTML + "...";

When the content is zeroed-out and rewritten, the overall images and other resources can be reloaded. (当内容被置零和重写时,可以重新加载整体图像和其他资源。)

outerHTML: full HTML of the element

outerHTML: full HTML of the element

This property includes the full HTML of the element. It looks similar to innerHTML plus the element itself, like here:

let div = document.createElement('div');
div.id = 'elem';
div.innerHTML = "Welcome to";
document.body.appendChild(div);
let b = document.createElement('b');
b.innerHTML = "w3cdoc";
div.appendChild(b);
alert(div.outerHTML); // <div id="elem"> Welcome to <b>w3cdoc</b></div>

Again, you need to be careful: in contrast to innerHTML , writing to outerHTML will not change the element, but will replace it in the DOM. It may sound strange, and that’s why let’s consider an example:

let div = document.createElement('div');
div.id = 'elem';
div.innerHTML = "Welcome to w3cdoc";
document.body.appendChild(div);
let d = document.querySelector('div');
// replace div.outerHTML with <p>...</p>
d.outerHTML = '<p>New element</p>'; // (*)
// 'div' is still the same
alert(div.outerHTML); // <div>Welcome to w3cdoc</div> (**)

In the line (*), div is replaced with <p>New element</p> . In the outer document, the content can be seen instead of <div>. But the most surprising fact is that in the line (**) the value of the old div variable is not changed.

The outerHTML assignment will not change the DOM element but remove it from the DOM, as well as, insert the new HTML in its place. (OuterHTML分配不会更改DOM元素,但会从DOM中删除它,并将新HTML插入其位置。)

So, an error can be made here easily. Modifying div.outerHTML and then continuing to work with div as if it had the new content. In fact, it doesn’t. This kind of thing can be correct for innerHTML, but not for outerHTML. (因此,在这里很容易出错。修改div.outerHTML ,然后继续使用div ,就好像它有新内容一样。事实上,事实并非如此。这种情况对于innerHTML可能是正确的,但对于outerHTML则不正确。)

You can also write to elem.outerHTML. But, note that it will not change the element you are writing to. (您也可以写入elem.outerHTML。但是,请注意,它不会更改您要写入的元素。)

nodeValue/data: Text Node Content

nodeValue/data: Text Node Content

The innerHTML property is acceptable only for element nodes. Text nodes and other node types have got a counterpart: nodeValue and data properties. In practice, they are almost the same. Still, there are some minor differences. The data is shorter, hence more convenient in use.

An illustration of reading the content of a text node along with the comment is shown below:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   Welcome
(欢迎学习)
   <!-- Comment -->
   <script>
     let text = document.body.firstChild;
     alert(text.data); // Welcome      
     let comment = text.nextSibling;
     alert(comment.data); // Comment
   </script>
 </body>
</html>

For text codes, there can be a reason for reading or modifying them. But what about the comments? (对于文本代码,阅读或修改它们可能是有原因的。但是评论呢?)

At times, programmers insert information or template instructions into HTML, as in the following example:

<!-- if isBook -->
<div>Welcome to Javascript book</div>
<!-- /if -->

Afterward, JavaScript will be capable of reading it from data property and process embedded instructions. (之后, JavaScript将能够从数据属性中读取并处理嵌入式指令。)

textContent: Pure Text

textContent: Pure Text

This property allows accessing the text inside the element. It’s about only the text without any <tag>.

Here is an example of using the textContent property:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <div id="text">
     <h1>Headline.</h1>
     <p>Welcome to w3cdoc</p>
   </div>
   <script>
     // Headline. Welcome to w3cdoc
(//Headline.欢迎来到w3cdoc)
     alert(text.textContent);
   </script>
 </body>
</html>

In the example above, you can notice that only the text is returned without the <tags>, as though the tags were cut out.

It is much more useful to write to textContent as it allows writing the text most safely. (写入textContent更有用,因为它可以最安全地写入文本。)

The “hidden” Property

The “hidden” Property (“隐藏”属性)

The “hidden” property indicates whether the element is visible or not. It can be used in HTML or assigned using JavaScript, as it is demonstrated in the following example:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <div>w3cdoc </div>
   <div hidden> First text "hidden"</div>
   <div id="elem">Second text "hidden"</div>
   <script>
     elem.hidden = true;
   </script>
 </body>
</html>

The “hidden” property technically operates the same as style=“display:none”. But it’s much shorter to write. A blinking element will look like this:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <div id="elem">A hidden element</div>
   <script>
     setInterval(() => elem.hidden = !elem.hidden, 1000);
   </script>
 </body>
</html>

And using only javascript code:

let div = document.createElement("div");
div.id = 'elem';
div.innerHTML = 'Welcome to w3cdoc';
document.body.appendChild(div);
setInterval(() => elem.hidden = !elem.hidden, 1000);

Additional Properties

Additional Properties (附加属性)

There exist additional properties of DOM elements. Here are the ones that depend on class, in particular:

  • value: means the value for <input> , <select> and <textarea> (HTMLInputElement,HTMLSelectElement, and so on).

  • href: for a <a href="…"> (HTMLAnchorElement).

  • id: means the value of the id attribute for the overall elements (HTMLElement).

Here is an example of using additional properties above:

<!DOCTYPE html>
<html>
 <head>
   <title>Title of the Document</title>
 </head>
 <body>
   <input type="text" id="inputElem" value="value">
   <script>
     alert(inputElem.type); // "text"
     alert(inputElem.id); // "inputElem"
     alert(inputElem.value); // value
   </script>
 </body>
</html>

And using only javascript code:

let input = document.createElement("input");
input.setAttribute("type", "text");
input.id = 'inputElem';
input.value = 'value';
document.body.appendChild(input);
console.log(input.type); // "text"
console.log(input.id); // "inputElem"
console.log(input.value); // value

Summary

Summary (概要)

To sum up, we can state that every DOM node belongs to a particular class. The classes, on their turn, represent a hierarchy. The set of methods and properties is the result of inheritance. The main DOM properties are nodeType,nodeName/tagName,innerHTML,outerHTML,nodeValue/data, textContent,hidden. There are also additional properties that depend on their class. (综上所述,我们可以声明每个DOM节点都属于一个特定的类。这些类轮流代表一个层次结构。方法和属性集是继承的结果。主要的DOM属性是nodeType、nodeName/tagName、innerHTML、outerHTML、nodeValue/data、textContent、hidden。还有其他依赖于其类的属性。)



请遵守《互联网环境法规》文明发言,欢迎讨论问题
扫码反馈

扫一扫,反馈当前页面

咨询反馈
扫码关注
返回顶部