Element search on the javascript side. Javascript and jquery element selection by class (class attribute). Methods used to search for a node or a collection of nodes in a tree

At the lesson, we will look at the cob: the Document Object Model (javaScript DOM) - the basis of dynamic HTML, we will see methods for accessing objects, and we will look at ways to process javascript

  • In general object- this is a warehouse type of data, which will change the meaningless value of the global module and allow you to save and win over the value behind their names.
  • Previously, we already learned about the understanding of javascript.

  • Javascript has the same understanding as DOM Document Object Model- Object model of the web-side (html-side).
  • Document tags or, as it seems, document nodes are the whole object.

Let's take a look at the diagrams object hierarchy in JavaScript, and those, de ієrarchії are found in the analysis of this topic document object.

The script element has the following attributes:

  • defer (clearance of the total engagement of the side).
  • Butt:

    Authority and attributes of the document object in javaScript

    The document object is the web page.

    Important: To bring to power those object methods in JavaScript, like when working with other objects, dot notation:

    tobto. the object itself is written with a start, then through a dot i without spaces it is indicated its power, attribute chi method

    object.authority object.attribute object.method()

    Let's look at the example:

    Butt: let html-document є tag

    My element

    and song for the new css style (navit two styles, the other is needed for setting):

    Required:

    1. set a new power of the object, give value to it and bring value to it;
    2. enter the value of the object's attribute;
    3. change the value of an object attribute.

    Let's take the task in order:
    ✍ Solutions:

      Since it is the language of javascript, then you can invent an object that asks whether there is power or whether there are any values. Ale for the cob we take access to the object (about access to the object will be reported below in this lesson):

      // Required access to object id var element = document.getElementById("MyElem"); element.myProperty = 5; // Assign power alert(element.myProperty); // Displayed in dialog box

      The next task is connected with the attribute of the object. Object attribute- Tse tag attributes. Tobto. our view has two: the class attribute with the values ​​small and the id attribute. Right behind the class attribute.

      Now dodamo the JavaScript to see the value of our object's attribute. The code is guilty buti after main tags:

      // Required access to object id var element = document.getElementById("MyElem"); alert(element.getAttribute("class")); // Displayed in dialog box

      І remaining task: change the value of the attribute. For whom we have style preparations big. Change the value of the class attribute to the style:

      // Required access to object id var element = document.getElementById("MyElem"); element.setAttribute("class","big");

      As a result, our element will become bigger and more popular with the blue color (class big).

    Now, let's take a look at the presentation of applied methods of work with attributes.

    Attribute Methods in JavaScript

    Attributes can be added, seen and changed. For which special method:

    • Adding an attribute (setting for a new value):
    • getAttribute(attr)

    • Rechecking the presence of this attribute:
    • removeAttribute(attr)

    Different ways to work with attributes

    Butt: Enter the value of the value attribute of the text block.


    ✍ Solutions:
    • Come on є text block:
    • varelem = document.getElementById("MyElem"); var x = "value";

    • Let's take a look at a few ways to retrieve the value of an attribute (to display it, use the alert() method):
    • elem.getAttribute("value" )

      elem.getAttribute("value")

      2. dot notation:

      elem.attributes .value

      elem.attributes.value

      3. bracket notation:


      Set attribute values you can also dekilcoma in the following ways:

      var x = "key"; // key - attribute name, val - attribute value // 1. elem.setAttribute("key", "val") // 2. elem.attributes.key = "val" // 3. elem.attributes[" key "] = "val" // 4. elem.setAttribute(x, "val")

      Authority of the body element

      Through the document object, you can navigate to the body of the document - the body tag - with a lot of power.

      For example, the body tag has two powers: width and height of the customer's window:

      document.body.clientHeight - client window height
      document.body.clientWidth - client window width


      And more importantly, as we have already recognized, tse those, that through the document object for the help of special methods, access to all elements of the page, such as tags, is provided.

      Important: With such a transition to the side tags, the script is guilty of being in the end of the element tree before closing the body ! Until the moment the script is finished, all the elements can still be marked by the browser on the screen

      js8_1 manager. Look at the information about the expansion of the window of the browser: for example, "resize browser window 600 x 400"

      Accessing Document Elements in JavaScript

      For access to objects or search for objects, a few options were transferred:

    1. Search by id(or the getElementById method), rotate a specific element
    2. Search for a tag name(or the getElementsByTagName method), rotate the array of elements
    3. Query for the name attribute(or the getElementsByName method), rotate the array of elements
    4. Through batkivsky elements(Removing all the goodies)

    Let's take a look at the skin from the options of the report.

    1. Accessing an element via its id attribute
    2. Syntax: document.getElementById(id)

      The getElementById() method rotates the element itself, which can be retrieved for data access

      Butt: On the side there is a text field with the attribute id="cake":

      ...

      Necessary


      ✍ Solutions:

      alert(document.getElementById("cake").value); // turn "near the cakes"

      You can vikonate those yourself, realizing the beast to the object through change:

      var a=document.getElementById("cake"); alert(a.value); // view the value of the value attribute, so. text "at the cakes"

    Important: The script is guilty of buti obov'yazkovo after the tag!

  • Access to an array of elements through the name of the tag name and after an additional array index
  • Syntax:
    document.getElementsByTagName(name);

    Butt: On the side, there is a text field (input tag) with the value attribute:

    ...

    Necessary: enter the value of the value attribute


    The getElementsByTagName method organizes access to all input elements (that is. to an array of elements input), navigate so that this element is single on the side. To go back to a specific element, for example the first one, then you need to specify the index (the array starts from the zero index).

    ✍ Solutions:

      Reverse to a specific element after the index:

      var a =document.getElementsByTagName("input"); alert(a.value); // turn "near the cakes"

  • Access to an array of elements behind the value of the name attribute
  • Syntax:
    document.getElementsByName(name);

    The getElementsByName("...") method turns array of objects, for which the name attribute is older than the value specified as a parameter to the method. Since there is only one such element on the side, the method rotates the array all the same (only with one single element).


    Butt: admissible in document є element:

    var element = document.getElementsByName("MyElem"); alert(element.value);

    This application has one element, but the order is set to the zero element of the array.

    Important: The method works only with these elements, for which the name attribute is passed to the specification: all tags form , input , a , select , textarea and other, more common ones.

    The document.getElementsByName method is not applicable to other elements of type div, p and the like.

  • Access to the home of the Batkiv element
  • Access to javascript buttons vydbuvaєtsya for additional power childNodes. Power to lay the object-batkovі.

    document.getElementById (parent) .childNodes ;

    document.getElementById(parent).childNodes;

    Let's look at the butt, de tags of the image placed in the container - div tag. In this way, the div tag is the father of these images, and the img tags themselves are clearly the caps of the div tag:

    <div id = "div_for_img" > <img src="pic1.jpg" /> <img src="pic2.jpg" /> <img src="pic3.jpg" /> <img src="pic4.jpg" /> </div>

    Now you can see the modal value of the elements in an array with caps, that is. img tags:

    var myDiv=document.getElementById("div_for_img"); // go to the container dad var childMas=myDiv.childNodes; // array of headers for (var i = 0; i< childMas.length;i++){ alert(childMas[i].src); }

    Please note that in order to iterate over the elements of an array of fields, you need to manually select a loop. Tobto. our application has a cycle:

    ... for (var a in childMas) ( alert(childMas[ a] .src ) ; )

    For (var a in childMas)( alert(childMas[a].src); )

  • Other ways to get to the elements
  • Other ways to look at on the example:

    <body> <formname="f"> <input type="text" id="t"> <input type = "button" id = "b" value = "button" > !}!} <select id="s" name="ss"> <option id = "o1" > 1</option> <option id = "o2" > 3</option> <option id = "o3" > 4</option> </select> </form>

    Access:

    ... // needless and outdated methods for accessing elements: alert(document.forms[0].name); // f alert(document.forms[0].Elements[0].type); // text alert(document.forms [0]. Elements [2]. Options [1]. // o2 alert(document.f.b.type); // button alert(document.f.s.name); // ss alert(document .f.s.options[1].id); // o2 // shorthand methods for accessing elements alert(document.getElementById("t").type); // text alert(document.getElementById("s").name); // ss alert(document.getElementById("s").options[1].id); // 02 alert(document.getElementById("o3") .text); // 4 ...

    ... // needless old methods for accessing elements: alert(document.forms.name); // f alert(document.forms.elements.type); // text alert(document.forms.elements.options.id); // o2 alert(document.f.b.type); // button alert(document.f.s.name); // ss alert(document.f.s.options.id); // o2 // shorthand methods for accessing elements alert(document.getElementById("t").type); // text alert(document.getElementById("s").name); // ss alert(document.getElementById("s").options.id); // 02 alert(document.getElementById("o3").text); // 4 ...

    Butt: For html documents, create a button and a text field. For the help of the script, change the background of the button (the power of style.backgroundColor of the button) and display "Vitayu!" at the text field (attribute value).

    HTML code:

    document.getElementById("t1").value = "Hi!""; document.getElementById("b1").style.backgroundColor = "red";!}!}

    Option 2:

    document.getElementById("t1") .setAttribute("value", "Hello!"); document.getElementById("b1" ) .style .backgroundColor = "red" ;

    document.getElementById("t1").setAttribute("value","Hello!"); document.getElementById("b1").style.backgroundColor = "red";

    Task Js8_2. Create text field tags appropriately to the thumbnail image. Give it a specific (specified little) id attribute value. For the help of the script, add to all numeric fields (which pass numeric values) the value "0"

    Verification of the correctness of the entered data forms

    Chi did not leave the field empty?

    Danim cannot be trusted. It is unreasonable to admit that the coristuvachi pіd the hour of the introduction of the data їх їх. So, it is necessary for the chogo to win javascript.

    In order to revise the text field is empty(for example, after filling in the data with the correct data, be it a questionnaire), then turn up to the point of value. As for the meaning of power, there is an empty row (""), then it is necessary to say something about this coristuvach.


    if(document.getElementById("name").value=="")

    In addition, you can do without a script. The input tag of a text field can have a pattern attribute. How this value is shown regularly in the course of rechecking data in a given text field form. What is an attribute pattern, then the form is not enforced until the text field is filled in correctly.
    For example, for re-verification, chi did not leave the field empty:

    Text replace numeric value: isNaN function

    What field is transferring entering a numeric value, and instead of someone else to enter the text, it is necessary to select the isNaN function (from English. "Chi is not a number?"), so that you check the type of data to be entered, and turn true when you enter text data instead of numeric data.

    Incl. If it is set to true , it is necessary to tell the clerk to get the correct format, so that. number.

    if(isNaN(document.getElementById("minutes").value))( prompt to enter numeric data);

    Given a page with elements to fill in:


    Snippet of html code:

    1 2 3 4 5 6 7 8 9 10 11 12 <form > Name:<input type="text" id="name">
    Number of donuts:<input type="text" id="donuts" >
    Khvilin:<input type="text" id="minutes">
    Podbag:<input type="text" id="subitog" >
    Gift:<input type="text" id="tax">
    Podbag:<input type="text" id="total">
    <input type = "submit" value = "submit" onclick = "placeOrder();" > !}!} </form> <script type="text/javascript"> ... </script>

    Name:
    Number of donuts:
    Khvilin:
    Podbag:
    Gift:
    Podbag:

    Required:
    Add the empty space of the fragment to the code, expanded below, in order to check the correctness of filling in the two text fields: im'ya(id="name") hvilin(id="minutes"). Vykoristovyte reverification for empty fields empty ("") that the correct format fills the numeric field (isNaN).

    * Vikonati task also for additional help of the pattern attribute of text fields for help.

    Script snippet:

    At the code they win to inspire folding minds, passed earlier.

    New understanding for you is the click of the function as a summary of the button:
    onclick="placeOrder();"
    By clicking on the button, the placeOrder() function will be called

    At some point, we can look at the method of the document object, which is recognized for node search or node collection for the entire document. Also, the methods of the node object (node), typing similar ones, but also among their daughter nodes.

    Methods used to search for a node or a collection of nodes in a tree

    At the front of the street, we looked at the authorities, for the help of which we can move around on a tree, and they know we need a knot. Prote, poshuk vuzlіv with the help of їхніх authorities occupies even more importantly and more effectively. If you want to know the nodes in the tree, the web explorer names are specially designed for either the document method or the node.

    getElementById() method

    The getElementById(elementID) method turns an element in a document that can have an identifier (id="elementID") as a Node object. If an element is designated by an identifier, it is not necessary that this method returns null .

    Depending on the standard, your document cannot have a small number of elements with the same value of the id attribute, that is. The value of an identifier can be unique at the boundaries of one document. Prote, if you have a document to find a number of elements from the assigned id , then the getElementById() method will turn the first known element.

    document.getElementById(elementID)

    This method takes one language parameter (elementID), which is in a row to retrieve the value of the element's id attribute, whichever you want to change.

    For example, change the color of the element text, which may be id="nameArticie" .

    Article name

    • 1 point
    • 2 point
    • 3 point

    getElementsByClassName() Method

    The getElementsByClassName(className) method rotates all known elements in the document (for document) or among child nodes (for node) so that it can be assigned to its class (class="className") as a NodeList object (collection of nodes). This method rotates the NodeList object, which is a collection of elements (nodes) that can be assigned in the parameters of this method to its class.

    To get the number of known nodes, you need to test the power of the length of the NodeList object. And in order to sort through all the nodes in the collection, you can speed up the upcoming cycle:

    Var elementsList = document.getElementsByClassName("list"); for (var i=0; i

    document.getElementByClassName(className);
    node(wuzole).getElementByClassName(className);

    This method has one language-specific parameter (className), which is in order to replace the name of the element class, as you want to. If you want to take away the elements that you can think of a small number of assigned classes, they are necessary in the parameters of this method to separate them for an additional sample. For example, take a collection of nodes, so that you can class classl and class2:

    Document.getElementsByClassName("classl class2");

    For example, change the color of the background of the elements, so that the list class can be:

    Article name

    • 1 point
    • 2 point
    • 3 point
    • 1 point
    • 2 point

    For example, possess a collection of elements (vuzlіv), so that the list class can be obtained. Dali take 2 vuzols from the collection, tobto. vuzol, scho maє іndex 1. After that, change the color of the background of the taken vuzol.

    //Remove the collection of elements to change the class list var elementsList = document.getElementsByClassName("list"); //Remove 2 nodes from the collection var secondList = elementsList; //Change the background color of the element secondList.style.backgroundColor = "red";

    getElementsByTagName() Method

    The getElementsByTagName(tagname) method rotates all found elements in the document (for document) or among child nodes (for node) so that the tag can be specified as a NodeList object (collection of nodes). The beginning of the song knot of the collection is assigned after the index. The number of elements (vuzlіv) in the collection starts from 0.

    document.getElementsByTagName(tagname);
    node(wuzole).getElementsByTagName(tagname);

    The Danish method may have one language parameter (tagname), which is in a row to avenge the name of the tag, as it is indicated by great letters. Also, in the value of the parameter, specify the row that should contain the asterisk ("*"), we take all elements in the document (for the document object) or all child elements of the node (for the node object).

    To control the number of known nodes to be included in the collection, it is necessary to win the power length of the NodeList object. And in order to sort through all the nodes in the collection, you can speed up the upcoming cycle:

    Var elementsList = document.getElementsByTagName("LI"); for (var i=0; i

    For example, change the background color of the LI elements:

    Article name

    • 1 point
    • 2 point
    • 3 point

    For example, take a collection of UL elements. Dali take 1 vuzol from the collection, tobto. node, which may have index 0. Next, select a collection of child nodes LI for this node. І nasamkinets change the font of the skin element in this collection.

    //Retrieve a collection of UL elements var elementsUL = document.getElementsByTagName("UL"); //Remove 1 node from this collection var elementUL = elementsUL; //Remove the collection of Child LI elements of the elementUL node var elementsLI = elementUL.getElementsByTagName("LI"); //Iterate through all the elements in the collection for (var i = 0; i

    getElementsByName() Method

    The getElementsByName(name) method turns all known elements in the document that can be specified by name (name attribute value) as a NodeList object (collection of nodes).

    Elements (woozles) are added to the collection in order, in which they grow near the tree. The beginning of the song knot of the collection is assigned after the index. The number of elements (vuzlіv) in the collection starts from 0.

    Var elementsList = document.getElementsByName("phone"); for (var i=0; i

    Note: The HTML5 name attribute will be deprecated, and replaced with the id attribute for most elements.

    document.getElementsByName(name)


    This method has one language-specific parameter (name), which is in a row to retrieve the value of the name attribute.

    For example, change the background color of the elements that the name attribute can have for the phone (name="phone") values:

    Phone: Other phones:

    querySelector() method

    The querySelector() method rotates the first element found in the document (for document) or the middle child node (for node) that matches the CSS selector passed as a parameter to this method. It is possible that the element is not matched by the CSS selector whose method evaluates to null .

    document.querySelector(cssSelector)
    node.querySelector(cssSelector)

    This method has one binding parameter (cssSelector), which is in a row how to change the CSS selector, depending on which element is selected.

    For example, change the color of the text of the first found element, which matches the #main p selector:

    ...

    ...

    For example, remove a collection of DIV elements from a document. Dali take 1 vuzol from the collection, tobto. node, which may have index 0. For which node, know the middle of its child nodes, the first element that matches the CSS selector h1+p . After that, change the font size of that element.

    //Remove the collection of DIV elements var elementsDIV = document.getElementsByTagName("DIV"); //Remove 1 node from this collection var elementDIV = elementsDIV; //Remove node p, recombine immediately after node h1 //Search for a node to work among the child nodes of a node that is taken into the change elementDIV var elementP = elementDIV.querySelector("h1+p"); //Change the font size of the element elementP.style.fontSize = "30px";

    querySelectorAll() method

    The querySelectorAll() method rotates all found elements in the document (for document) or among child nodes (for node) to match the CSS selector passed as a parameter to this method in a NodeList object (collection of nodes). The return to the nodes of the collection is based on the index. The number of elements (vuzlіv) in the collection starts from 0.

    To remove the number of known nodes, it is necessary to win the power of the length of the NodeList object. And in order to sort through all the nodes in the collection, you can speed up the upcoming cycle:

    Var elementsList = document.querySelectorAll("#main p"); for (var i=0; i

    document.querySelectorAll(cssSelector);
    node(wuzole).querySelectorAll(cssSelector);

    This method has one binding parameter (cssSelector), which is in a row how to change the CSS selector, depending on how many elements are selected. To insert a number of selectors for the parameters of this method, it is necessary to separate them among themselves through a coma.

    For example, change the color of the text of the elements, so that they match the #main p selector:

    ...

    ...

    For example, select a child node that can have the id attribute of the sidebar values. Change the color of the background of the child elements of the p-node, cut off on the front edge:

    //get the element (wuzole) that can be id="sidebar" var sidebar = document.getElementById("sidebar"); //define the collection of nodes that match the "p" selector var elementsListP = sidebar.querySelectorAll("p"); //Iterate through all the elements in the collection for (var i = 0; i

    manager

    Write code in your JavaScript with the methods getElementById() , getElementsByClassName() , getElementsByTagName() , querySelector() , querySelectorAll() for upcoming tasks:

    1. Otrimat all p elements, roztashovanі in block main;
    2. Remove the aside block, expand the container div;
    3. Remove the footer block, fold in the body container.

    The skin of the head of the viskonat yakomog is able to use a large number of different ways.

    To make the script instantly work as a side element, you need to know which element on the back. For which JavaScript, there are a few ways. Knowing the element, you will be attracted by the serpentine, and nada, through the change of the script, you will turn to the element and work with it like a dії.

    Search by id

    Like the id attribute of a task element, the element can be identified by its id. The simplest way. The element lookup is followed by the getElementById() help method of the document global object.

    document.getElementById(id)

    Parameters:

    id - id of the element, which one you need to know. id - in a row, that vin can be in the paws.

    Let's create a side, add an element on it and set its id, and in the script we know this element:

    HTML code:

    JavaScript:

    var block = document.getElementById("block"); console log(block);

    Knowing the element, we added the change block and entered the change into the console. Open the browser console, it may have values ​​for the element.

    So how to search by id is the simplest and most effective way, often victorious itself yoga. If it is necessary to work with this element in the script, then in the code of the side of this element, set the id attribute. І know element by id.

    Check out the class

    The getElementsByClassName() method allows you to know all the elements that belong to the same class.

    document.getElementsByClassName(class)

    Parameters:

    class - class of elements, what you need to know

    The method rotates a pseudo-array to retrieve the elements found. Pseudo-array of wines is called that which for the new one does not practice a lot of methods of arrays. And yet the head of power is emptied - you can turn to whatever element of the array. Navіt yakscho found only one element, but all the same searched for the array.

    Dodamo on the side of the element and ask them class. Part of the elements is placed in the middle of the block, which we created earlier. For the rest of the time, let's create a pose in a block. The sense of this will be a little bit of wisdom. Now the side looks like this:

    HTML code:

    JavaScript:

    Found only those elements, yakі raztashovani in blots.

    Search for a tag

    getElementsByTagName() method to know all elements with a particular tag. Vin also rotates the pseudo-array from the known elements.

    document.getElementsByTagName(tag)

    Parameters:

    tag - element tag, what you need to know

    We know all the tags p, yakі є on the side:

    var p = document.getElementsByTagName("p"); console log(p);

    This method can be loaded not to the entire document, but to a specific element. Find out all the p tags that are in the block.

    Search by selector

    Understand the querySelector() and querySelectorAll() methods to find the elements that match the single selector. Tobto, you will know the elements, up to some letters of the style, yakby of the values ​​of such a selector. For some reason, the presence of such a selector in the sidebar style is not obv'yazkovo. These methods are not related to CSS. The querySelectorAll() method knows all the elements that match the selector. And the querySelector() method knows one element, which is the first one in the side code. These methods can replace all methods of searching for elements that were looked at earlier, even if there is a selector for id, a selector for tag and many others.

    document.querySelector(selector)

    document.querySelectorAll(selector)

    Selectors are written the same way as in CSS, just don't forget to put your paws on.

    Dodamo on the side of the list and we know it behind the selector. We only joke about one element and we know for sure that the wine will be the first, that the wine is one on the side. Therefore, in this case, it is better to twist the querySelector() method. Ale, when using the victorious method, it is necessary to vouch for what you put on the side, but you can also add the same elements. Vtim, it is necessary to use more methods.

    HTML code:

    These methods can shukati elements not in the whole document, but in the middle of a single element.

    At the butt, they were more selective for the tag. Try to know the elements of the side for the help of other selectors.

    Susidni elements

    For the found element, you can know the suid_v. The skin element is the object and the essential elements can be taken away through the power of the object. The power of the received element ahead will avenge the front element, and the power of nextElementSibling will avenge the next element.

    element.previousElementSibling

    element.nextElementSibling

    We know the element that follows the block:

    Child elements

    The power of children to avenge an array with child elements.

    element.children

    We know the child elements of the blocks.

    The DOM standard transfers the element's lookup request. The same methods getElementById, getElementsByTagName and getElementsByName.

    More powerful methods and tricks to promote javascript libraries.

    Search by id

    The best way to know an element in the DOM is to take yogo for id. For which wiki is to be created document.getElementById(id)

    For example, the next code is to change the color of the text to a black div "e with id="dataKeeper" :

    Document.getElementById("dataKeeper").style.color = "blue"

    Search for a tag

    The next step is to remove all the elements with the song tag and the middle of the list of needs. For that, document.getElementsByTagName(tag) . You turn an array of elements to make such a tag.

    For example, you can take another element (numbering in the array starting from zero) with the li tag:

    Document.getElementsByTagName("LI")

    Well, getElementsByTagName can be called not only for document, but also for any element, which may be a tag (not text).

    When tsimu will be found tі ob'єkti, yakі znahodyatsya pіd tsim element.

    For example, the next call will take a list of LI elements that appear in the middle of the first div tag:

    Document.getElementsByTagName("DIV").getElementsByTagName("LI")

    Take away all the goodies

    Viklik elem.getElementsByTagName("*") rotate list of current children of node elem in the order of their detour.

    For example, on this DOM:

    Code like this:

    Var div = document.getElementById("d1") var elems = div.getElementsByTagName("*") for(var i=0; i

    Vivede sequence: ol1, li1, li2.

    Search for name: getElementsByName

    The document.getElementsByName(name) method turns all elements that have the same name (name attribute) as the given one.

    Vіn praciuє only with these elements, but the specification explicitly passes the name attribute: not form , input , a , select , textarea and other, more rare ones.

    The document.getElementsByName method is not applicable to other elements of type div, p and the like.

    Other ways

    Explore other ways to search the DOM: XPath, cssQuery, etc. As a rule, they are implemented by JavaScript libraries to extend the standard browser capabilities.

    There is also a getElementsByClassName method to search for elements by class, but it doesn't work in IE, so nothing looks like it in a clean way.

    Often pardon pov'azana z vіdsutnistyu letters s the name of the getElementById method is the same as the letter є in other methods: getElement s Byname.

    The rule here is simple: one element - Element, many - Element s. Usі methods *Element s* Rotate the list of nodes.


    In the past lesson, the getElementsByTagName method was looked at, which rotates the array ( group) sidebar elements on the tag name.

    There are three practical JavaScript jobs here, and we'll look at the getElementById method, which turn the direction on the element, oriented by its unique identifier id .

    The getElementById method, like getElementsByTagName, is the method of the document object.

    The name of the method is translated literally: retrieve element id.

    Be-what element ( tegu) of a web document, you can assign your own id-identifier, for sure element become unique And before the new one, you can take access to the robot itself with it.

    Return respect e: in the name of the method in the last word Element there is no letter s ( on the view in the getElementsByTagName method). This is done for clarity and to confirm that the method is to serve the selection of the element.

    Poor explanation for the code snippet above...

    • img tag ( images f) may id-identifier penguin;
    • for the additional getElementById method, the img tag itself is selected by the penguin identifier;
    • at the change unique forceful on the selected tag;
    • dalі you can work with the tag, yak z object through change unique , similar to before, as the work with the Date object was carried out through quite a change.

    After denying access to the element ( tegu) web pages by id-identifier behind the additional method getElementById , we already work with it, like with the Object, and therefore, we need access to the attributes of the tag, like to the authority of the Object.

    Otzhe, the meaning of attributes is already the meaning of authority.

    We continue to practice with the front butt ...

    "Thoughtful Penguin">

    Explanation for the attached code...

    • img tag ( images f) multiple attributes: src - file address, width and height - image width and height, alt - alternative text;
    • denying access to the tag after the help of the getElementById method, as an object, we will deny access to the attributes of the tag, as to the authority of the object;
    • A attribute values now already power values;
    • JavaScript has access to the authority of an object through a dot. Send alt - alternative text of the img tag behind the alert method on the screen.

    I hope you didn't get lost in everything. It is necessary to understand at once, what is considered on the programming level of JavaScript and on the level of document layout.

    The img tag is an Object unique;

    The attribute of the tag width and alt is the value of the Object's power;

    Attribute value "128" and "Thoughtful Penguin"- Tse meaning of power;

    // Axis as it looks from javascript positions:

    var unique = (

    width : "128" ,

    alt : "Thoughtful Penguin"

    }

    The axis uses the getElementById method in such a way, which turns the request on any element ( tag) of the web page, as well as the unique identifier id . Then the robot was carried out with this element on equal javascript already like an object...

    Next check out what: like in the front row, here - when working with the getElementById method

    jQuery has more options for selecting elements of a web document.