dotslashlu
dotslashlu

Reputation: 3401

Can jQuery manipulate inserted elements?

I'm a freshman to jQuery. I think it's reasonable that jQuery could manipulate elements added by code, but I found it couldn't just now.

$(function(){
    $("#addVideo").click(function(){
         $("#publisher").append("<div id='choseType'><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>");
    })      
    $("#choseType input:eq(0)").click(function(){
     $(this).addClass("selected");
    })
})

Is it jquery's limitation or my code's fault? It seems if I put the second click() function into the first one it will run correctly, but it will only run once(if I remove the appended #choseTypeand append it again the second click won't work.).Then how do I manipulate code added elements? Thanks!

Upvotes: 2

Views: 1227

Answers (2)

Joseph
Joseph

Reputation: 119867

$(function(){
    $("#addVideo").click(function(){

        //create new content, and append to publisher
        //also, reference the new content
        var newContent = $("<div><input type='button' value='video'> <input value='music' type='button'> <input type='button' value='X'></div>").appendTo('#publisher');

        //then add a handler to input in the context of the new content
        $("input:eq(0)", newContent).click(function(){
            $(this).addClass("selected");
        });
    })    
})

Upvotes: 2

adeneo
adeneo

Reputation: 318312

Delegate the event to an element that is not dynamic:

$(document).on('click', "#choseType input:eq(0)", function(){
    $(this).addClass("selected");
});

And ID's are unique!

Upvotes: 4

Related Questions