jQuery (2) Modify elements and find elements

Table of Contents

1. Modify elements

1. Modify content

2. Modify attributes

3. Modify style

2. Search according to the relationship between nodes

1. DOM two relationships, six attributes

2. jQuery two relationships, eight attributes


1. Modify elements

Same as DOM, the content, attributes, and styles of elements can be modified. Still note that all functions related to modification are used for both purposes.

1. Modify content

(1) The original HTML content between the element’s start tag and the end tag

//DOM
element.innerHTML

//jQuery
$element.html("New Content")
//If there is no "new content", it means to get the content of the element, if there is, it means to modify the original content to new content (one function has two uses)

(2) The plain text content between the element’s start tag and the end tag

//DOM
element.textContent

//jQuery
$element.text("New Content")

(3) Value of form element

//DOM
element.value

//jQuery
$element.val("new value")

Example: Use element content to implement form validation;

<body>
<h1>Contents and values of operating elements</h1>
<form action="">
Username:<input name="uname">
<span></span><br>
Password:<input type="password" name="upwd">
<span></span><br>
<input type="submit" value="Submit registration information">
</form>
<script src="js/jquery-1.11.3.js"></script>
<script>
//When correct, use the image: "<img src='img/ok.png'>"
//When the name is wrong: "<img src='img/err.png'>The user name must be between 3 and 9 digits!"
//When the password is wrong: "<img src='img/err.png'>The password must be between 6~8 characters!"
//DOM 4 steps

//Verify username
//1. Find the element that triggered the event
//The element that triggers the event is the text box, and it is verified when the text box loses focus.
$(":text")
//2. Bind event handler function
.blur(function () {
var $this = $(this);
//3. Find the element to be modified
//Find the span element next to the current text box
var $span = $this.next();
//4. Modify elements
// 4.1 Get the content of the current text box
var value = $this.val();
// 4.2 for verification
if (value.length >= 3 & amp; & amp; value.length <= 9) {
// 4.3 Modify the content of span
$span.html(`<img src='img/ok.png'>`);
} else {
$span.html(`<img src='img/err.png'>Username must be between 3~9 characters!`);
}
})

\t\t// verify password
// 1. Find the element that triggered the event
//The event is triggered by the password box
$(":password")
// 2. Bind event handling function
.blur(function () {
var $this = $(this);
// 3. Find the element that needs to be modified
// The span element before the current password box
var $span = $this.next();
// 4. Modify elements
// 4.1 First get the contents of the password box
var value = $this.val();
// 4.2 for verification
if (value.length >= 6 & amp; & amp; value.length <= 8) {
$span.html(`<img src='img/ok.png'>`);
} else {
$span.html(`<img src='img/err.png'>Password must be between 6~8 characters!`);
}
})
</script>
</body>

2. Modify attributes

(1) HTML standard attributes of string type

//DOM/
//old core DOM/
Element.getAttribute("attribute name")
Element.setAttribute("Attribute name", "New value")
//New HTML DOM
element.propertyname=newvalue

//jQuery
$element.attr("Attribute name", "New value")
$element.prop("property name", "new value")

Example: Click on the picture to switch to the next one;

<body>
<h1>Manipulate the attributes of elements</h1>
<img src="img/1.jpg" alt="1">
<script src="js/jquery-1.11.3.js"></script>
<script>
//DOM 4 steps
// 1. Find the element that triggered the event
// Find img
$("img")
// 2. Bind event handling function
.click(function () {
// 3. Find the element to be modified
//Modify img itself
var $this = $(this);
// 4. Modify elements
// 4.1 Take out the alt attribute value in the current img element and convert it to an integer
var alt = parseInt(
$this.attr("alt")
);
// 4.2 If the attribute value is < 4, then + + ; otherwise, change it back to 1
if (alt < 4) {
alt + + ;
} else {
alt = 1;
}
// 4.3.3 Combine the new alt value into the image path and put it into the src attribute of the current img
$this.attr({
src: `img/${alt}.jpg`,
alt: alt
});
})
</script>
</body>

(2) HTML standard attributes of bool type

//DOM
//HTML DOM
element.attribute name

//jQuery
$element.prop("property name", new bool value)

(3) Custom extended attributes

//DOM
//Old core DOM:
element.getAttribute()
element.setAttribute()
//HTML5:
element.dataset.attribute name

//jQuery
$element.attr()

For example: click on a small picture to switch to a large picture;

<body>
  <img src="img/1.jpg" data-click data-target="img/1-l.jpg" class="my-small">
  <img src="img/2.jpg" data-click data-target="img/2-l.jpg" class="my-small">
  <img src="img/3.jpg" data-click data-target="img/3-l.jpg" class="my-small">
  <img src="img/4.jpg" data-click data-target="img/4-l.jpg" class="my-small">
  <hr />
  <img src="img/1-l.jpg" class="my-big">

  <script src="js/jquery-1.11.3.js"></script>
  <script>
    //Click on the small picture to display the big picture in my-big below
    //DOM 4 steps
    // 1. Find the element that triggered the event
    // Find all img elements with data-click attribute
    $("[data-click]")
      // 2. Bind event handling function
      .click(function () {
        // 3. Find the element to be modified
        // Modify the large image below
        var $big = $(".my-big");
        // 4. Modify elements
        // 4.1 Get the large image path saved by the data-click attribute value of the currently clicked img
        var src = $(this).attr("data-target");
        // 4.2 Set the large image path to the src attribute of the large image
        $big.attr("src", src);
      })
  </script>
</body>

3. Modify style

//DOM
//Modify inline style
Element.style.css attribute="new value"
//Get the complete style
getComputedStyle(element)


//jQuery
//Get css attribute value, modify css attribute value
$element.css("css attribute","new value")
//If no new value is given in .css(), the bottom layer of .css() automatically executes the getComputedStyle() operation to obtain the attribute value.
//If a new value is given in .css(), the bottom layer of .css() automatically executes the .style.css attribute and performs modification operations.

Batch modify multiple css attributes of an element:

//DOM
Element .className="class name" //Only all classes can be replaced as a whole, and it is inconvenient to modify one of the classes.

//jQuery
$element.addClass("className") //Add a class
$element.removeClass("className") //Remove a class
$element.hasClass("className") //Determine whether there is a certain calss
$element.toggleClass("className") //Switch back and forth between having or not having a class

Example: Implement a two-state button;

<head lang="en">
  <meta charset="UTF-8">
  <title></title>
  <style>
    .btn {
      padding: 5px 10px;
      border-radius: 3px;
      border: 1px solid #aaa;
      outline: none;
    }
    .up {
      background: #fff;
      color: #333;
    }
    .down {
      background: #ddd;
      color: #fff;
    }
  </style>
</head>
<body>
  <button class="btn up">Two-state button</button>
  <script src="js/jquery-1.11.3.js"></script>
  <script>
    //Two-state button: Let the button's class switch between up and down
    //DOM 4 steps
    //1. Find the element that triggered the event
    $(".btn")
      //2. Bind event handler function
      .click(function () {
        //3. Find the element to be modified
        var $this = $(this);
        if ($this.hasClass("down")) {
          $this.removeClass("down")
        } else {
          $this.addClass("down")
        }
        //$(this).toggleClass("down") //Equivalent to if else
        //4. Modify elements
      })
  </script>
</body>

1. Two relationships in DOM, six attributes

(1) Father-son relationship

element.parentElement //parent element
Element.children //All direct child elements
Element.firstElementChild //The first direct child element
Element.lastElementChild //The last direct child element

(2) Brotherhood

Element.previousElementSibling //Previous sibling element
Element.nextElementSibling //Next sibling element

2. jQuery two relationships, eight attributes

(1) Father-son relationship

$element.parent() //parent element
$element.children() //All direct child elements
$element.children("selector") //Only select individual direct child elements that meet the requirements
$element.find("selector") //Select elements that meet the requirements among all descendants
$element.children(":first-child") //The first direct child element
$element.children(":last-child") //The last direct child element

(2) Brotherhood

$element.prev() //Previous brother
$element.prevAll("selector") //All previous brothers:
$element.next() //Next sibling
$element.nextAll("selector") //All brothers after that
$element.siblings("selector") //Except the current element, all other sibling elements

Case: tab page effect;

<head>
  <meta charset="UTF-8">
  <style>
    .tabs {
      list-style: none;
      padding: 0
    }

    .tabs a {
      text-decoration: none;
      color: #000;
      padding: 6px 12px;
      display: inline-block;
    }

    .tabs>li {
      float: left;
      border-bottom: 1px solid #000;
    }

    .tabs>.active {
      border: 1px solid #000;
      border-bottom: 0;
    }
  </style>
</head>

<body>
  <h1>Use attribute selector to switch tab header</h1>
  <ul class="tabs">
    <li class="active">
      <a data-toggle="tab" href="#">Ten yuan set meal</a>
    </li>
    <li>
      <a data-toggle="tab" href="#">Twenty yuan package</a>
    </li>
    <li>
      <a data-toggle="tab" href="#">Thirty yuan package</a>
    </li>
  </ul>
  <script src="js/jquery-1.11.3.js"></script>
  <script>
    //DOM 4 steps
    //1. Find the element that triggered the event
    // Find all label buttons with the data-toggle attribute and the attribute value is tab
    $("[data-toggle=tab]")
      //2. Bind event handler function
      .click(function () {
        //3. Find the element to be modified
        //What needs to be modified is the parent element of the a tag and the parent's sibling elements
        //4. Modify elements
        var $this = $(this);
        // 4.1 First add the .active attribute to the parent element
        $this.parent().addClass("active");
        // 4.2 Cancel the .active attribute for other sibling elements of the parent element
        $this.parent().siblings().removeClass("active");

        //4.1 and 4.2 can be combined into one (chain type)
        //$this.parent().addClass("active").siblings().removeClass("active");
      })
  </script>
</body>

The effect is as shown in the figure. Every time you click on a package, you will switch to the current package.