This is the 28th day of my participation in the August Challenge

Hi, I’m Ken

Author: Please call me Ken Link: juejin.cn/user/109118… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

🌊🌈

Part of the content and pictures of the article are from the Internet. If you have any questions, please contact me (there is an official account in the introduction of the home page).

This blog is suitable for just contactJSAnd the friends who want to review after a long time.

🌊🌈

6.3_ Obtaining Elements

In development, if you want to manipulate a part of the page (such as controlling the display or hiding of a DIV element, modifying the content of a DIV element, etc.), you need to obtain the element corresponding to that part and then operate on it.

Here are some common ways to get elements.

6.3.1_ Get elements by ID

The getElementById() method is provided by the Document object to find elements. This method returns the element with the specified ID, or null if no element with the specified ID is found, or undefined if multiple elements with the specified ID exist. It is important to note that JavaScript is case sensitive, so you must follow the writing specification when writing, otherwise the program will report errors.

Example: Demonstrate the use of the document.getelementById (‘ id ‘) method,

<body>

<div id="box">hello</div>

<script>
var Obox = document.getElementById('box');
console.log (Obox);
       
Hello
console.log (typeof Obox);// The result is object console.dir (Obox);// the result is: div#box
</script> </body> Copy the code

In the above code, a < div> tag is defined in line 2. Since the document is loaded from top to bottom, the < script> tag and JavaScript code in lines 3 to 8 are written below line 2 so that the div element can be retrieved correctly. Line 4 takes the HTML element with id box and assigns it to the variable Obox. Note that id values cannot be added with “#” as CSS does, as getElementByld (” #box “) is incorrect. The console.dir() method on line 7 is used to view the properties and methods of an object in the console.

6.3.2_ Get elements by label

There are two ways to get an element based on its title name: from a Document object and from an Element object.

The code is shown below,

document.getElementByTagName ('Tag name');
element.getElementsByTagName ('Tag name');
Copy the code

Element in the above code is a general term for the element object. An element object can be used to look up children or descendants of the element, achieving the effect of looking up elements locally, whereas a Document object looks up elements from the entire document.

Because there can be multiple elements with the same tag name, the above method does not return a single element object, but rather a collection. This collection is an array-like object, or pseudo-array, that can access elements with indexes like an array, but not with methods like push(). You can also prove that it is not an Array using array.isarray ().

Case: demonstration,

<! doctypehtml>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>

<ul>
	<li>apple</li>
	<li>banana</li>
	<li>watermelon</li>
	<li>cherry</li>
</ul>

<ol id="ol">
	<li>green</li>
	<li>blue</li>
	<li>white</li>
	<li>red</li>
</ol>

<script>
	var lis = document.getElementsByTagName('li');
HTMLCollection(8) [li, li, li, li, li, li, li, li, li, li, li]
	console.log(lis);  

  • apple
  • console.log(lis[0]); // Iterate over all the elements in the collection for(var i = 0; i < lis.length; i++) { console.log(lis[i]); } // Get the element from the element object var ol = document.getElementById('ol'); HTMLCollection(4) [li, li, li, li] console.log (ol.getElementsByTagName('li'));
    </script> </body> </html> Copy the code

    In the above code, we define a < ul> unordered list and a < OL > ordered list with id OL. Demonstrates the document. The getElementsByTagName () usage, which returns all < li > tag element collections of objects.

    Note that even if there is only one LI element on the page, the result is still a collection, and if there is no li element on the page, an empty collection will be returned.

    It can be seen from the output result of the code that LIS is a collection object containing 8 Li elements. The constructor of this object is HTMLCollection. Returns the first li element in the collection. The element objects in the collection are printed in turn by traversal. Demonstrates element. The getElementsByName usage (), the element must be a single object, is not a collection, so you need to use the document. The getElementsById () to obtain element, a method is called again. Use getElementsByTagName() to get all the Li elements in OL.

    • Note that the collection retrieved by the _ getElementsByTagName() method is a dynamic collection, meaning that when the page adds tags, elements are automatically added to the collection.

    6.3.3_ Get elements by name

    Get elements by name attribute should use the document. The getElementsByName () method, which is commonly used in access to form elements.

    The value of the name attribute does not have to be unique; multiple elements can have the same name, such as checkboxes and checkboxes in a form.

    Example: Demonstrate checkboxes,

    <! doctypehtml>
    <html>
    <head>
    <meta charset="utf-8">
    <title></title>
    
    </head>
    <body>
    
    <p>Please choose your favorite fruit (multiple choices)</p>
    <label><input type="checkbox" name="fruit" value=The word "apple">apple</label>
    <label><input type="checkbox" name="fruit" value="Banana">banana</label>
    <label><input type="checkbox" name="fruit" value="Watermelon">watermelon</label>
    
    <script>
    	var fruits = document.getElementsByName('fruit');
    	fruits[0].checked = true;
    </script>
    
    </body>
    </html>
    Copy the code

    In the code above, the getElementsByName() method returns a collection of objects, retrieving elements using an index. Fruit [0]. Checked: True; checked: true; fruit [0]. Checked: True; fruit [0]. Checked: True;

    6.3.4_HTML5 New obtaining method

    HTML5 for the Document object new getElementsByClassName(), querySelector() and querySelectorAIl() methods, in the use of browser compatibility issues need to be considered.

    1. According to the class name for the document. ElementsByClassName ()

    Document. ElementsByClassName () method, is used to obtain certain elements set by the name of the class.

    Let’s demonstrate this with the example code,

    <! doctypehtml>
    <html>
    <head>
    <meta charset="utf-8">
    <title></title>
    
    
    
    </head>
    <body>
    
    <span class="one">English</span>
    <span class="two">mathematics</span>
    <span class="one">Chinese language and literature</span>
    <span class="two">physical</span>
    
    <script>
    	
    	var Ospan1 = document.getElementsByClassName('one');
    	var Ospan2 = document.getElementsByClassName('two');
    	Ospan1[0].style.fontWeight = 'bold';
    	Ospan2[1].style.background = 'red';
    	
    </script>
    
    </body>
    </html>
    Copy the code

    In the above code, the getElementsByClassName() method is used to get a collection of classes named one and two, respectively, stored in Ospan1 and Ospan2. Using subscript form, find and set the fontWeight attribute of the first element with subscript 0 in Ospan1 to bold, and the backgound attribute of the second element with subscript 1 in Ospan2 to red.

    2. QuerySelector () and querySelectorAIl ()

    The querySelector() method returns the first element object of the specified selector. The querySelectorAll() method returns a collection of all element objects for the specified selector.

    Case: demonstration,

    <! doctypehtml>
    <html>
    <head>
    <meta charset="utf-8">
    <title></title>
    
    </head>
    <body>
    
    <div class="box">Box 1</div>
    <div class="box">Box 2</div>
    <div id="nav">
    	<ul>
    		<li>Home page</li>
    		<li>product</li>
    	</ul>
    </div>
    
    <script>
    
    	var firstBox = document.querySelector('.box');
    	console.log(firstBox); // Get the first div whose class is box
    	
    	var nav = document.querySelector('#nav');
    	console.log(nav); // Get the first div with id nav
    	
    	var li = document.querySelector('li');
    	console.log(li); // get the first li matched
    	
    	var allBox = document.querySelectorAll('.box');
    	console.log(allBox); // Get all divs whose class is box
    	
    	var lis = document.querySelectorAll('li');
    	console.log(lis); // Get all li matches
    	
    </script>
    
    </body>
    </html>
    Copy the code

    As you can see from the above code, when you use the querySelector() and querySelectorAlI() methods to get the elements of the operation, you simply write the tag name or CSS selector name. When retrieving an element by its class name, prefix the class name with “. To get elements by ID, prefix the id with “#”.

    6.3.5_document Object properties

    The Document object provides properties that can be used to get elements in a document, for example, get all form tags, image tags, and so on.

    Properties of the document object:

    attribute instructions
    document.body Returns the body element of the document
    document.title Returns the title element of the document
    document.documentElement Returns the HTML element of the document
    document.forms Returns references to all Form objects in the document
    document.images Returns a reference to all Image objects in the document

    The body attribute in the Document object is used to return the body element, and the documentElement attribute is used to return the HTML element of the root node of the HTML document.

    Example: Get the body element and HTML element,

    <! doctypehtml>
    <html>
    <head>
    <meta charset="utf-8">
    <title></title>
    
    </head>
    <body>
    
    <script>
    	
    	var bodyEle = document.body;
    	console.dir(bodyEle);
    	
    	var htmlEle = document.documentElement;
    	console.log(htmlEle);
    	
    </script>
    
    </body>
    </html>
    Copy the code

    In the above code, lines 3 and 4 get the body element as document.body and print the result on the console as console.dir(). Lines 5 and 6 get the HTML element as document.documentElement and print the result.

    That’s the end of today’s introductory study

    Peace

    🌊🌈

    A Ken HTML, CSS introduction guide (a)_HTML basics a Ken HTML, CSS introduction guide (b)_HTML page elements and attributes a Ken HTML, CSS introduction guide (c)_ text style attributes Ken HTML, CSS introduction guide (four)_CSS3 selector Ken HTML, CSS introduction guide (five)_CSS box model Ken HTML, CSS introduction guide (six)_CSS box model Ken HTML, CSS introduction guide (seven)_CSS box model Ken’s Getting Started with HTML and CSS (8)_CSS box model Ken’s Getting Started with HTML and CSS (9)_ Floating and Positioning Ken’s Getting Started with HTML and CSS (10)_ Floating and Positioning Ken’s getting Started with HTML and CSS (11)_ Floating and positioning Ken’s introduction to HTML and CSS (12)_ The application of forms The introduction to HTML and CSS (13)_ the application of forms (14)_ the application of forms the introduction to HTML and CSS (15)_ the application of forms A Ken HTML, CSS introduction guide (16) _ multimedia technology

    Suggest collection 】 【 HTML dry share | challenge the shortest possible time to take you into the HTML (18) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (19) suggest collection 】 【 HTML dry share | challenge the shortest time take you into the HTML (20)

    Suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (a) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (2) suggest collection 】 【 share | JS dry challenge the shortest time to take you into the JS (3) the share | JS dry Recommended collection 】 challenge the shortest time take you into the JS (4) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (5) suggest collection 】 【 share | JS dry challenge the shortest time take you into the JS (6) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (7) Suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (eight) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (nine) suggest collection 】 【 share | JS dry challenge the shortest time to take you into the JS (10) 【 share | JS dry goods Recommended collection 】 challenge the shortest time take you into the JS (11) suggest collection 】 【 share | JS dry challenge the shortest possible time to take you into the JS (12)

    🌊🌈 About postscript:

    Thank you for reading, I hope to help you if there is a flaw in the blog, please leave a message in the comment area or add contact information in the home page of the personal introduction of private chat I thank every little partner generous advice

    Original is not easy, “like” + “attention” thanks for your support ❤