Home  >  Article  >  Web Front-end  >  How to add elements inside div with jquery

How to add elements inside div with jquery

青灯夜游
青灯夜游Original
2021-11-15 15:19:324003browse

Method: 1. Use append() to insert elements to the "end" inside the div element, the syntax is "$("div").append(element)"; 2. Use prepend(), Elements can be inserted into the "beginning" inside the div element with the syntax "$("div").prepend(element)".

How to add elements inside div with jquery

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

jquery adds elements in div

1. Use the append() method

in In jQuery, we can use the append() method to insert content "at the end" inside the selected element.
Syntax:

$(A).append(B)
  • means inserting B at the end of A.

Example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style type="text/css">
        div{
			height: 100px;
			background-color:orange;
		}
    </style>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                var $strong = "<strong>欢迎来到PHP中文网!</strong>";
                $("div").append($strong);
            })
        })
    </script>
</head>
<body>
    <div>hello!</div><br />
    <input id="btn" type="button" value="插入"/>
</body>
</html>

How to add elements inside div with jquery

2. Use prepend() method

in In jQuery, we can use the prepend() method to insert content to the "beginning" inside the selected element.

Syntax:

$(A).prepend(B)
  • means inserting B at the beginning of A.

Example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <style type="text/css">
        div{
			height: 100px;
			background-color:orange;
		}
    </style>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                var $strong = "<strong>欢迎来到PHP中文网!</strong>";
                $("div").prepend($strong);
            })
        })
    </script>
</head>
<body>
    <div>hello!</div><br />
    <input id="btn" type="button" value="插入"/>
</body>
</html>

How to add elements inside div with jquery

Related video tutorial recommendation: jQuery Tutorial (Video)

The above is the detailed content of How to add elements inside div with jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn