Create Div Tag & Elements Before Another Div Tag In jQuery

Wikitechy | 3642 Views | jquery | 02 Jun 2016

 

  • In jQuery the before (content) method is used for inserting content before each of the matched elements.

Syntax:

$(selector).before(content,function(index))

Sample Code: 

Parameter     

Description

content  

Required. Specifies the content to insert (can contain HTML tags)

Possible values:

HTML elements

jQuery objects

DOM elements

function(index,html)

Optional.

ü index - Returns the index position of the element in the set


<!DOCTYPE html>
<html>
<head> 
    <title>

        wikitechy-create controls dynamically in jquery
    </title> 
    <script
 src="http://code.jquery.com/jquery.js"></script>
    <script>

    $(document).ready(function(){
        $("button").click(function(){
            $("div").before("Text inserted before div Tag<br />");
        });
    });
    </script>
</head>
<body>
    <button>
WikiTechy - Add new controls and div element dynamicaly</button>
    <p>
Click above button to dynamically add div element below</p>
    <div
id="SecondPara">Hi from Wikitechy </div>
</body> 
</html>

Code Explanation:


    Inside the <script src= ” http://code.jquery.com/jquery.js “> </script> the ajax library has been called using the (src)=source attribute.

    Here we have created the elements button, paragraph and div section .

    The $(document).ready(function);  - specifies that the document to be fully loaded and ready before working with it, in order to prevent any jQuery code from running before the document is finished loading.

    $("button").click(function(){ - here is the button click event, which has been called here as element selector whose element “button” has been assigned for the click function.

    Here we use the element selector “div” and we assign it, before the function for the element “div”.so that the text will be appended before the div element.

Sample Output:


    Here in this output we have shown the button” WikiTechy - Add new controls and div element dynamically” initially there is no div element which will be added dynamically as shown here.


    Here in this output we have shown the button” WikiTechy-Add new list item” clicked for 1st time where the new div element “Text inserted before div tag” has be added before the text “Hi from wikitechy” in the window as shown.


    Similarly, here in this output we have shown the button” WikiTechy-Add new list item” clicked for 2nd time where the new div element “Text inserted before div tag” has be added before the text “Hi from wikitechy” in the window as shown.




Workshop

Bug Bounty
Webinar

Join our Community

Advertise
<