Chapter 3: jQuery attributes and styles

Time:2020-1-23

1. Attributes and styles of jQuery. Attr() and. Removeattr()

Each element has one or more attributes whose purpose is to give additional information about the corresponding element or its content. For example: in the IMG element, SRC is the attribute of the element, which is used to mark the address of the picture.

There are three main DOM methods for operating features: getattribute method, setAttribute method and removeaattribute method. Even so, there are still many problems in the actual operation, let alone here. In jQuery, you can use an attr () and removeattr () to solve all problems, including compatibility

In jQuery, we use the attr () method to get and set element attributes. Attr is the abbreviation of attribute, which is often used in jQuery DOM operations

Attr() has four expressions

  1. Attr (passed in attribute name): get the value of the attribute
  2. Attr (attribute name, attribute value): set the value of the attribute
  3. Attr (property name, function value): set the function value of the property
  4. Attribute: set multiple attribute values for the specified element, that is: {attribute name one: “attribute value one”, attribute name two: “attribute value two” }

Removeattr() delete method

. removeattr (attributename): removes an attribute for each element in the matched element collection

Advantage:

Both attr and removeattr are encapsulated by jQuery for attribute operation. Calling this method directly on a jQuery object makes it easy to operate on attributes and does not need to understand the different attribute names of browsers

Attention:

There is a distinction between the concepts in DOM: attribute and property are translated as “property”, and JS advanced programming is translated as “property” and “property”. Simply understand, attribute is the attribute of DOM node

For example: ID, class, title, align, etc. commonly used in HTML:

<div id=”immooc”></div>

Property is the DOM element as an object, and its additional contents, such as tagName, nodeName, nodeType, defaultchecked, and defaultselected. Prop() method is used for value or assignment

You need to use attr to get attribute and prop to get property

Source code of case: – attributes and styles of style chapter / 3.1jquery. Attr() and. Removeattr(). HTML)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    < title > jQuery attributes and styles. Attr() and. Removeattr() < / Title >
    <style>
    input {
        display    : block;
        margin     : 10px;
        padding    : 10px;
        background : #bbffaa;
        border     : 1px solid #ccc;
    }
    </style>
    <script></script>
</head>
<body>
    <h2>. attr() and. Removeattr()</h2>
    <h3>.attr</h3>
    <form>
        < input type = "text" value = "set value" / >
        < input type = "text" value = "get value" / >
        < input type = "text" value = "callback splicing value" / >
        < input type = "text" value = "delete value" / >
    </form>

    <script type="text/javascript">
        //Find the first input and set the value of the attribute value through attr
        $("input:first").attr('value','.attr( attributeName, value )')
    </script>

    <script type="text/javascript">
        //Find the second input and get the value of the attribute value through attr
        $("from input:nth-child(2)").attr('value')
        console.log( $("input:eq(1)").attr('value') )
    </script>

    <script type="text/javascript">
        //Find the third input and set the properties by using a function
        //The final required attribute value can be returned according to other attribute values on the element
        //For example, we can associate new values with existing values:
        $("input:eq(2)").attr('value',function(i, val){
            console.log(i)
            console.log(val)
            Return 'set' + Val through function
        })
    </script>

    <script type="text/javascript">
        //Find the fourth input and delete the attribute by using removeattr
        $("input:eq(3)").removeAttr('value')
        console.log( $("input:eq(3)").removeAttr('value') )
    </script>
</body>
</html>

Attributes and styles of query. Attr() and .removeAttr()”>
<span>See the Pen
JQuery’s attributes and styles. Attr() and. Removeattr() by gadget (@ xiaodongxier)
on CodePen.</span>
</p>
<script async></script>

2. HTML () and. Text () of jQuery’s attributes and styles

It is a common DOM operation to read and modify the HTML structure or the text content of an element. JQuery provides two convenient methods. HTML () and. Text ()

. HTML () method

Get the HTML content of the first matching element in the collection or set the HTML content of each matching element. There are three specific uses:

  1. . HTML () does not pass in a value, which is to get the HTML content of the first matching element in the collection
  2. . HTML (htmlstring) sets the HTML content of each matching element
  3. .html (function (index, oldhtml)) is used to return a function to set HTML content

matters needing attention:

The. HTML () method uses the innerHTML attribute of the DOM to handle it internally, so you need to pay attention to one of the most important issues in setting and obtaining,This operation is for the entire HTML content (not just the text content)_

. text() method

Get the text content combination of each element in the matching element set, including their descendants, or set the text content of each element in the matching element set as the specified text content. There are three specific uses:

  1. . text () gets the merged text of each element in the matching element collection, including their descendants
  2. . text (textstring) the text used to set the content of the matching element
  3. . text (function (index, text)) is used to return a function to set the text content

matters needing attention:

. text() result returns a string containing the combined text of all matching elements

Similarities and differences between. HTML and. Text:

  1. The method operation of. Html is the same as that of. Text, except that it is different for processing objects
  2. . HTML deals with element content,. Text deals with text content
  3. . HTML can only be used in HTML documents,. Text can be used in both XML and HTML documents
  4. If the object being processed has only one child text node, the result of HTML processing is the same as that of text
  5. Firefox does not support innerText property. It uses similar textcontent property. The. Text () method integrates the support of two properties, so it can be compatible with all browsers

Source code of case: – HTML () and. Text (). HTML of attributes and styles of style / 3.2jquery)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    HTML () and. Text () of jQuery's attributes and styles < / Title >
    Html() and. Text() / imooc. CSS "type =" text / CSS ">
    <script></script>
</head>
<body>
    <h3>. html() and. Text()</h3>
    <div class="left first-div">
        <div class="div">
            <a>:first-child</a>
            <a>Second element</a>
            <a>:last-child</a>
        </div>
        <div class="div">
            <a>:first-child</a>
            <a>Second element</a>
            <a>:last-child</a>
        </div>
    </div>
    < H4 > display the content obtained by HTML method < / H4 >
    <p></p>
    < H4 > display the content obtained by text method < / H4 >
    <p></p>
    <script type="text/javascript">
        //Display the content obtained by HTML method
        //. HTML () is the entire HTML document structure
        $('p:first').text($(".first-div").html()) 
    </script>
    <script type="text/javascript">
        //Shows what the text method gets
        //. text () is a collection of text content
        $('p:last').text($(".first-div").text()) 
    </script>
    <script type="text/javascript">
        //Replace text content with. Text() method
        $(". Left a: first"). Text ('replace contents of first a element ')  
    </script>
    <script type="text/javascript">
        //Replace HTML structure with. HTML () method
        $(". Left div: first"). Text ('child nodes of the entire div have been replaced ')
    </script>
    <script type="text/javascript">
        //Through the callback of. Text(), get the original content, modify and reassign
        $(".left a:first").text(function (idnex, text) {
            Return 'add new text content' + text
        })
    </script>
</body>
</html>

HTML () and. Tex of properties and styles of T () >
<span>See the Pen
Properties and styles of jQuery: HTML () and. Text () by widget (@ xiaodongxier)
on CodePen.</span>
</p>
<script async></script>

3. JQuery attributes and styles. Val ()

There is a. Val () method in jQuery that is mainly used to process the values of form elements, such as input, select and textarea.

.val () method

  1. . val() no parameter, get the current value of the first element in the matched element set
  2. . val (value), set the value of each element in the matched element set
  3. . val (function), a function to return the set value

matters needing attention:

  1. Select element is processed through. Val(). When no selection is selected, it returns null
  2. The. Val() method is used to set the value of the form’s field
  3. If the select element has the multiple attribute and at least one of the selected items is selected, the. Val () method returns an array containing the values of each selected item

Summary of differences between. Html(),. Text() and. Val():

  1. . HTML (),. Text (), and. Val () are all used to read the content of the selected element. Only. HTML () is used to read the HTML content of the element (including HTML tags),. Text () is used to read the plain text content of the element, including its descendent elements,. Val () is used to read the “value” value of the form element. Among them. Html() and. Text() methods cannot be used on form elements, while. Val() can only be used on form elements; in addition, when. Html() method is used on multiple elements, it only reads the first element;. Val() method is the same as. Html(), if it is applied on multiple elements, it can only read the “value” value of the first form element, but. Text() is different from them, if. Text() should be used When used on multiple elements, the text content of all selected elements will be read.
  2. . HTML (htmlstring),. Text (textstring) and. Val (value) are three methods used to replace the content of the selected elements. If the three methods are applied to multiple elements at the same time, the content of all the selected elements will be replaced.
  3. . html(),. Text(),. Val() can use the return value of the callback function to dynamically change the content of multiple elements.

Case source code: – style chapter / 3.3jquery attributes and styles. Val(). HTML)

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    Attributes and styles of < title > jQuery. Val() < / Title >
    <style>
        p {
            color: red;
            margin: 4px;
        }
        b {
            color: blue;
        }
    </style>
    <script></script>
</head>
<body>
    <h3>.val()</h3>
    <select id="single">
        < option > mooc.com
        < option > blog Park < / option >
    </select>
    <select id="multiple" multiple="multiple">
        <option selected="selected">imocc</option selected="selected">
        < option > mooc.com
        < option selected = "" > blog Park < / option selected = "selected" >
    </select>
    <input type="text" value="click a button" />
    <p></p>
    <script type="text/javascript">
        //Single select, return the first
        $("p").text($("#single").val() )
        Console. Log ($("single"). Val()) // mooc.com
    </script>
    <script type="text/javascript">
        //Multiple select is selected, return to [imocc "," blog Park "]
        $("p").text($("#multiple").val() ) 
        Console. Log ($("#multiple"). Val()) / ["imocc", "blog Park"]
    </script>
    <script type="text/javascript">
        //Select a form and modify the value
        $("input [type ='text ']). Val ('modify field of form') 
    </script>
</body>
</html>

Query properties and styles. Val() “>
<span>See the Pen
JQuery’s properties and styles. Val() by gadget (@ xiaodongxier)
on CodePen.</span>
</p>
<script async></script>

Interrogative answer

  1. Case in Section 2$(". Left a: first"). Text ('replace contents of first a element ')Get the first a element under the first div sub element, and$(". Left a: last"). Text ('replace contents of first a element ')What we get is the last a element under the second div sub element. Why is it under the second div sub element? But if you use$(". Left a: nth child (1)"). Text ('replace contents of first a element ')For selection, the first a element of two div sub elements is selected.