Aravind Bharathy
Aravind Bharathy

Reputation: 1610

Appending to dynamic content

I have a set a dynamically created divs with the same class name. Now I want to append a entirely new div to all of the above mentioned divs.

Say the class name is extra-upper-block

At the end of my page I have this code

<script>
    //function call to load dynamic content
</script>
<script>
    $('.extra-upper-block').append('<div>New Div</div>');
</script>

This throws an error in chrome's console

Uncaught TypeError: undefined is not a function  

But when this code is executed in chrome's console after the page is loaded, it works! Why doesn't it work even when I load the dynamic content before executing the append command. Help?

Upvotes: 0

Views: 2229

Answers (4)

Shaunak D
Shaunak D

Reputation: 20626

Use jQuery class selector.

$(document).ready(function(){
    $('.extra-upper-block').append('<div>New Div</div>');
});

Wrap your code in $(document).ready() for jQuery to get the elements available, and include jQuery file reference.

Note : .append() method is a part of jQuery.

Demo

Upvotes: 1

MrCode
MrCode

Reputation: 64526

document.getElementsByClassName returns an array-like object, you can't use it like jQuery, you need to access the individual element in a loop. Also, use appendChild on DOM elements, because they don't have an append method (like jQuery does).

Also, you are trying to append a string <div>New div</div>, you can't directly do that with a DOM element, so instead you can create the div element like so:

Demo

var elements = document.getElementsByClassName('extra-upper-block');

for(var i=0; i<elements.length; i++){
    var newDiv = document.createElement('div');
    newDiv.appendChild(document.createTextNode('New div'));
    elements[i].appendChild(newDiv);
}

Note: querySelectorAll has better cross browser support than this. If you have jQuery included you can simply do:

$('extra-upper-block').append('<div>New Div</div>');

As you can see, with jQuery you can append a string directly.

Upvotes: 1

Esko
Esko

Reputation: 4207

Append is a function in jQuery, try this:

<script>
$(function() {
      $('.extra-upper-block').append('<div>New Div</div>');
});  
</script>

Upvotes: 0

Vlas Bashynskyi
Vlas Bashynskyi

Reputation: 2014

try writing

document.getElementsByClassName('extra-upper-block')[0].appendChild(document.createElement('div'));

Upvotes: 0

Related Questions