Althorn05
Althorn05

Reputation: 3

Accessing elements that have just been added with jQuery.add()

I currently have a javascript function that adds an element to the DOM using jQuery .add() method, and then immediately attempts to access it (in this case by adding a class, waiting a bit and removing it again)

elem = "<p id="new">added element</p>"
jQuery("body").add(elem)
jQuery("#new").addClass("red")
setTimeout(function(){
    jQuery(".new").removeClass("red")
},1000)

The problem is that the jQuery selector can't find the .new element. All the solutions I've found to similar problems involve binding a click/mouse event to the element after it's loaded, which is not what i'm looking for in this case. I've also looked at alternatives to jQuery.add(), but only came up with jQuery.append() which results in the same problem.

If it's of any relevance, the function this code snippet is in lies outside of the jQuery(document).ready() function.

tl;dr version:
How do I go about manipulating (eg. adding a class to) an element just after it's been added using jQuery.add()?

Upvotes: 0

Views: 114

Answers (3)

Tamil Selvan C
Tamil Selvan C

Reputation: 20229

Change elem = "<p id="new">added element</p>" to elem = '<p id="new">added element</p>'

elem = '<p id="new">added element</p>';
jQuery("body").add(elem)
jQuery("#new").addClass("red")
setTimeout(function(){
    jQuery("#new").removeClass("red")
},1000)

Upvotes: 0

PSL
PSL

Reputation: 123739

change . to #

jQuery("#new").addClass("red")
setTimeout(function(){
    jQuery("#new").removeClass("red")
});

or if you meant class then change your markup to have class instead of id.

elem = '<p class="new">added element</p>'

.new targets element with class new and #new targets the element with id new.

.add() doesn't add element to DOM. You can use append to add the element as the last child of body by doing

jQuery("body").append(elem)

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388436

You got it all wrong

  1. Your string concatenation is not properly escaping "
  2. You are using id and class selectors missed up (id - # and class - .)
  3. .add() is not used to add a new element, you need to use .append()

Try

elem = '<p class="new">added element</p>'
jQuery("body").append(elem)
jQuery(".new").addClass("red")
setTimeout(function(){
    jQuery(".new").removeClass("red")
}, 1000)

Demo: Fiddle

I may write it as

var elem = $('<p class="new">added element</p>').appendTo('body').addClass('red');
setTimeout(function(){
    elem.removeClass("red")
}, 1000);

Demo: Fiddle

Upvotes: 1

Related Questions