js Base-DOM-Attribute and CSS

DOM - Properties and CSS

1. Attributes

HTML elements consist of a tag and a set of name/value pairs called attribute s.

1. HTML attributes as attributes of Element s

The HTMLElement object representing an HTML document element defines read and write attributes that map the HTML attributes of the element.

HTMLElement defines generic HTTP properties such as id, Title lang, and dir, as well as event handler properties such as onclick.

Specific Element subtypes define specific attributes for their elements.For example:

var image = document.getElmentById("myimage") 
var imgurl = image.src //The src attribute is the URL of the image
image.id === "myimage" // Decide the id of the picture to look for

Similarly, we can set the form submission properties for an element.

var f = document.forms[0]; //The first <form>in the document 
f.action = "submit.php"; //Set Submitted URL
f.method = "POST"; //HTTP Request Type

HTML property names are case insensitive, but JavaScript property names are case sensitive.Conversion from HTML property names to JavaScript property names should be lowercase.However, if an attribute name contains more than one word, the first letter of a word other than the first word is capitalized, such as zIndex, backgroundColor

Note: Some HTML attribute names are reserved words in JavaScript.For example, the class and for attributes of HTML become className and htmlFor attributes in JavaScript.

2. Get and set non-standard HTML properties

Element nodes provide four ways to manipulate attributes.

  • getAttribute()//Get Attributes
  • setAttribute()//Set Attribute
  • hasAttribute()//Detect whether an attribute exists
  • removeAttribute()//Delete Attribute

2.1 Element.getAttribute()

The getAttribute() method returns the specified attribute of the current element node.Returns null if the specified property does not exist.

<div id="top" name="div"></div>

var t = document.getElementById('top');
t.getAttribute('name'); //div

2.2 Element.setAttribute()

setAttribute()Method is used to add attributes to the current element node.If an attribute already exists, it is equivalent to modifying an existing attribute.

t.setAttribute('name','top2'); 

2.3 Element.hasAttribute()

The hasAttribute() method returns a Boolean value indicating whether the current element node contains the specified attribute.

t.hasAttribute('name')  //true 

2.4 Element.removeAttribute()

The removeAttribute() method is used to remove attributes from the current element node.

t.removeAttribute('name') 
//<div id="top"></div>

3. dataset properties

Any lowercase attribute name prefixed with "data-" is legal in HTML5 documents.

HTML5 also defines dataset properties on Element objects.This property refers to an object whose properties correspond to the data-property with the prefix removed.Therefore, dataset.x should hold the value of the data-x attribute.The hyphenated attribute corresponds to the name of the hump nomenclature attribute: the data-jquery-test attribute becomes the dataset.jqueryTest attribute.

<div id="top" data-tip="title"></div>

var t=document.getElementById('top');
t.dataset.tip //title
t.dataset.tip = 'title2'

Be careful: dataset Attributes are elements data-Real-time, two-way interface for properties.Set or delete dataset An attribute is equivalent to setting or removing the corresponding element data-Properties.

4,As Attr Node Properties

Node Type definition attributes Properties.For non Element Any node of the object, this property is null. about Element Object, attributes Attributes are read-only class array objects that represent all the attributes of an element.Similar NodeList,attributes Objects are also real-time and can be accessed using a numeric index, which means that all the attributes of an element can be enumerated.It can also be indexed by an attribute name.

document.body.attributes[0]  //The first attribute of the <body>element 
document.body.attributes.bgcolor // bgcolor attribute of <body>element
document.body.attributes['ONLOAD'] // The onload attribute of the <body>element.

The property node object has name and value attributes, which correspond to the property name and value, and are equivalent to the nodeName and nodeValue attributes.

<div id="top"></div>

var t = document.getElemntById('top');
t.attributes[0].name // "id"
t.attributes[0].nodeName // "id"

t.attributes[0].value // "top"
t.attributes[0].nodeValue // "top"

5,The content of an element

5.1 As HTML Elemental content of

read Element Of innerHTML Property returns the content of that element as a string tag.

<div id="top">content</div>

var t=document.getElementById('top');
t.innerHTML // content
t.innerHTML = 'Content 2';
//<div id="top">content2</div>

HTML5 Standardized outerHTML Properties.only Element Node definition outerHTML Properties, Document Nodes do not.

insertAdjacentHTML()

Will be arbitrary HTML The tag string is inserted at the specified element's "adjacent" position.The first parameter is a string with one of the following values: beforebegin","afterbegin","beforeend"And " afterend". Tags are the second parameter of this method.

5.2 Element content as plain text

The standard method is to use Node Of textContent Attributes:

<div id="top"><p>content</p></div>

var t = document.getElementById('top');
t.textContent // content

textContent Attributes are all descendants of the element that will be specified Text Nodes are simply concatenated.

textContent Attributes in IE Not supported.stay IE You can use the innerText Attribute to replace.

5.3 As Text Element content of a node

nodeValue Properties, save Text The content of the node.

//The following textContent() function recursively traverses the child nodes of an element and then connects the text of all Text nodes in a descendant node.

function textContent(e){ 
var child,type,s=''; //s Save text for all child nodes
for(child = e.firstChild; child !=null;child =child.nextSibling){
type = child.nodeType;
if(type === 3 || type === 4) //Text and CDATSection nodes
{
s += child.nodeValue;
}else if( type === 1){
s += textContent(child);
}
return s;
}
}

The CDATASection node, which is a subtype of Text in an XML document, represents the contents of a CDATA segment.

2. CSS

Cascading Style Sheet (CSS) is a standard for specifying the visual representation of HTML documents.

2.1 Scripted Inline Styles

Changing the style attribute of individual document elements is the most straightforward way to script CSS.

The value of the style property is not a string, but a CSSStyleDeclaration object.The JavaScript property of the style object represents the CSS property specified by the style in HTML code.

<div id="top"></div>

var t = document.getElementById('top');
t.style.fontSize = '15px';
t.style.color = 'red';

//or
t.setAttribute('style','background:red;');

Be careful: CSSStyleDeclaration Property name and actual in object CSS Property names differ.If one CSS The property name contains one or more hyphens, CSSStyleDeclaration Attribute names should be formatted to remove hyphens and capitalize the letters immediately following each hyphen.For example: CSS attribute border-left-width The value of JavaScript Medium Pass borderLeftWidth Property access.

Also, when a CSS Properties (such as float)stay JavaScript When the corresponding name is a reserved word, add " css"Prefix to create legal CSSStyleDeclaration Name.

float -- cssFloat

Note: All positioning attributes need to include units.

t.style.left = 300  //error

t.style.left = '300px' //Correct

style Object's cssText It can also be used to read, write or delete entire style Properties.

t.style.cssText

t.style.cssText = 'background:red';

style Object's three methods for reading and writing inline CSS Rules.

  • setProperty(propertyName,value): Set up a CSS Properties.
  • getPropertyValue(propertyName): Read a CSS Properties.
  • removeProperty(propertyName): Delete a CSS Properties.

    //The first parameter of these three methods is the CSS property name, without rewriting the conjunction line.
t.style.setProperty('background-color','red'); 
t.style.getPropertyValue('background-color');
t.style.removeProperty('background-color');

All of the above methods can only read and write inline styles (set with style), if you want to get referenced or pseudo element styles?

The getComputedStyle() method of the window object is used!

window.getComputedStyle()

getComputedStyle() is a method of browser window objects that can be used to obtain a calculation style for an element.This method requires two parameters, the first is to get the element of its calculation style, and the second is required, usually a null or empty string, but it can also be a string that names a CSS pseudo-object, such as': before','after','first-line'or': first-letter'.

The getComputedStyle() method returns a CSSStyleDeclaration object that represents all the styles applied on the specified element (or pseudo-object).

<style> 
#top{ line-height:30px;}
#top:before{content:'before';color:red};
</style>
<div id="top" style="background:red"></div>

var t = document.getElementById('top');
window.getComputedStyle(t,null).lineHeight //30px
window.getComputedStyle(t,':before').content // "before"

In addition, you can use window.getComputedStyle Object's getPropertyValue()Method to get the properties.

window.getComputedStyle(t,null).getPropertyValue('line-height');  //30px, no hyphens required 

Differences between computed style CSStyleDeclaration objects and objects representing inline styles:

  • The properties of a calculation style are read-only
  • The value of the calculation style is absolute.Relative units such as percentages and points will all be converted to absolute values.
  • Compliance attributes are not calculated and are based on the most basic attributes only.For example, instead of querying the margin attribute, use marginTop, and so on
  • The cssText property of the calculated style is undefined.

In IE, each HTML has its own currentStyle property, and its value is also a CSSStyleDeclaration object.

function getStyle(dom, attr) { 
var value = dom.currentStyle ? dom.currentStyle[attr] : getComputedStyle(dom, false)[attr];
return parseFloat(value);
}

getStyle(t,'lineHeight'); //30

2.2 Scripted CSS Classes

Changing or adding the class attribute value of HTML is also a way to change the inline style attribute.

Since the identifier class is a reserved word in JavaScript, the HTML attribute class uses the JavaScript code of the className in JavaScript code.

T.className ='attention'; //Set class property 
T.className +='attention2'; //Add class attribute
t.className =''; //Delete all classes
t.className = t.className.replace('attention2','); //delete class named attention2

In HTML5, each element defines a classList attribute whose value is a DOMTokenList object: a read-only class array object that contains the individual class names of the elements and is real-time.There are four ways to do this:

element.classList.add()   //Add to 
element.classList.remove() //delete
element.classList.contains() //Whether to include
element.classList.toggle() //Add if no class name exists, otherwise delete

2.3 Scripted Stylesheet

When scripting style sheets, we encounter two types of objects that need to be used.

The first is an element object, represented by <style>and <link>elements, which contain or reference a stylesheet.

The second is the CSSStyleSheet object, which represents the stylesheet itself.The document.styleSheets property is a read-only class array object that contains a CSSStyleSheet object representing the style sheet associated with the document.

2.3.1 Getting Style Sheets

The StyleSheet object is a class array object.

var sheets = document.styleSheets; 
var s = document.styleSheets[0];

Of course, you can also get it through the selector

<style id="styleElement"> 
body{ background:red }
</style>

document.querySelector('#styleElement').sheet
//Equivalent to document.styleSheets[0]

Note: The styleSheets array contains link nodes and style stylesheets

2.3.2 Turn style sheets on and off

The <style>, <link> elements, and CSSStyleSheet objects all define a disabled attribute that can be set and queried in JavaScript.As the name implies, if the disabled property is true, the stylesheet is closed and ignored by the browser.

document.styleSheets[0].disabled = true; //close the first stylesheet 
//or
var s = document.querySelectorAll('styleElement');
s[0].disabled = true; //Select style sheet through selector

Note: The disabled property can only be set in JavaScript, not in HTML statements.

2.3.3 Query, insert, and delete style sheets

The elements of the document.styleSheets[] array are CSSStyleSheet objects.The CSSStyleSheet object has a CSSRules[] property that points to a class array object that contains all the rules of the stylesheet:

document.styleSheets[0].cssRules[0] 

Use different property name rules instead of CSSRules in IE.

The elements of the CSSRules[] or rules[] array are CSSRule objects.The difference is that in standard API s, the CSSRule object contains all the CSS rules, including directives such as @import and @page; in IE, the rules[] array contains only the style rules that actually exist in the stylesheet.

The CSSRule object has two properties that are used.

  • SelectectText is a rule's CSS selector that references a writable CSSStyleDeclaration object that describes the style associated with the selector.
  • The cssText property to get the text representation of the rule.
var s = document.querySelector('#styleElement').sheet; or document.styleSheets[0];

s.cssRules[0].cssText //body { background: red; }
s.cssRules[0].selectorText ///body

Each CSS rule also has a style property that points to an object for reading and writing specific CSS properties.

s.cssRules[0].style.background   //red 
s.cssRules[0].style.background = 'blue';

The styleSheets object also has two methods, insertRule(), and deleteRule(), to add and delete rules.However, the above two methods are not supported in IE, but there are addRule() and removeRule() methods.

The first parameter of the insertRule method is the string representing the CSS rule, and the second parameter is the insertion position of the rule in the cssRules object.The parameter to the deleteRule method is the position of the rule in the cssRules object.

s.insertRule(' h1 { color:blue; }',0);  //The h1 element defaults to blue 
s.deleteRule(1);

//IE
s.addRule('h1','color:blue',s.cssRules.length);
s.removeRule(1);

2.3.4 Create a new style sheet

document.createElement('style'); 
//or
var l = document.createElement('link');
l.setAttribute('rel', 'stylesheet');
l.setAttribute('type', 'text/css');
l.setAttribute('href', 'example.css');
document.head.appendChild(l);
document.head.appendChild(linkElm);
//IE
document.createStyleSheet()

2.4 CSS Events

In HTML5, CSS animation events are provided so that we can monitor the animation process.

2.4.1 TransiionEnd Event

The transitionEnd event is triggered after the transition of CSS is completed.

function onTransitionEnd(elem, handler,capture) { 
elem.addEventListener('transitionend', handler,capture);
elem.addEventListener('webkitTransitionEnd', handler,capture);
elem.addEventListener('mozTransitionEnd', handler,capture);
};

2.4.2 animationstart events, animationend events, animationiteration events

CSS animation has three events:

  • animationstart event: Triggered at the beginning of the animation.
  • Animamationend event: Triggers when the animation ends.
  • animationiteration event: triggered when a new animation cycle begins.If the animation-iteration-count property is equal to 1, the event does not trigger, that is, it plays only one round of CSS animation and does not trigger the animation event.
element.addEventListener("animationstart", listener, false); 
element.addEventListener("animationend", listener, false);
element.addEventListener("animationiteration", listener, false);

Of course, in the actual use process, you need to add a prefix.

element.addEventListener('webkitAnimationStart',listener,false); 

We can also control the state of the animation.
The animation-play-state property controls the state of the animation (pause/play), which requires a browser prefix.

element.style.webkitAnimationPlayState = "paused";  
element.style.webkitAnimationPlayState = "running";

Keywords: Attribute Javascript IE html5

Added by priti on Thu, 23 May 2019 19:08:13 +0300