Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Difference between $('div/') and $('div') in jQuery?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 248
    Comment on it

    Example of $('div/') in jQuery:

    $('<div/>').addClass('test');

    Example of $('div') in jQuery:

    $('div').addClass('test');
    

    Explanation of difference between $('div') and $('<div/>') in jQuery using above example:

    In the first example, $('<div/>')  will create a new div element but this div element is not added to DOM tree unless it is not appended  to any DOM element using appendTo() method. So, the code $('<div/>').addClass('test') will create a new div element and adds css class called "test" but it is not in the DOM tree. 

    In the second example, $('<div>') selects all the div element present on the page. So code $('div').addClass('test') will select all the div element present on the page and adds css class "test" to them and will be present in DOM tree.

    With $('<div/>'), only new element gets created but it is still not added to DOM. One have to append it to any other element using jQuery methods. For example, to append this newly created div to body, use below jQuery code.

    $('<div/>').addClass('test').appendTo('body')

    This will append newly created div to the body element thus making it present in DOM tree.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: