2

How to add new elements to DOM in jQuery

 2 years ago
source link: https://www.laravelcode.com/post/how-to-add-new-elements-to-dom-in-jquery
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to add new elements to DOM in jQuery

  1219 views

  1 year ago

jQuery

Ad byValueimpression

Use the jQuery append() or prepend() method

You can add or insert elements to DOM using the jQuery append() or prepend() methods. The jQuery append() method insert content to end of matched elements, whereas the prepend() method insert content to the beginning of matched elements.

The following example will show you how to add new items to the end of an HTML ordered list easily using the jQuery append() method. Let's try it out and see how it works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Elements to DOM</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("ol").append("<li>list item</li>"); 
        });
    });
</script>
</head>
<body>
    <button>Add new list item</button>
    <ol>
        <li>list item</li>
        <li>list item</li>
        <li>list item</li>
    </ol>
</body> 
</html>
Similarly, you can add elements to the beginning of matched elements.

The following example will demonstrate how to add an HTML heading at the beginning of a paragraph element using the jQuery prepend() method.

ExampleTry this code »
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Elements to DOM</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("p").prepend("<h1>This is a heading</h1>"); 
        });
    });
</script>
</head>
<body>
    <p>This is a paragraph.</p>
    <button>Add heading</button>
</body> 
</html>
Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]

Related Articles

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK