Appending to dynamic content - javascript

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?

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

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.

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

Append is a function in jQuery, try this:
<script>
$(function() {
$('.extra-upper-block').append('<div>New Div</div>');
});
</script>

Related

Unable to select <a> based on its text and then add an attribute named "target" to it using jQuery

I have the following link inside my web page:
Attachments and Documents
Now I want to select this link based on its text "Attachments and Documents", and set a target attribute for it.
So I tried the following:
var tgb = $('a:contains("Attachments and Documents")')[0];
tgb.attr('target', '_blank');
But I got the following exception :
TypeError: tgb.attr is not a function
As soon as you use index ([0]), tab is no more a jQuery object. To get the jQuery function attr() you have to wrap tgb with $:
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
// to demonstrate result
console.log(tgb)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
attr() is a jQuery function. You need to target your variable using jQuery methods
$(tgb)
Hope this helps :)
var tgb = $('a:contains("Attachments and Documents")')[0];
$(tgb).attr('target', '_blank');
console.log(tgb);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
var tgb = $('a:contains("Attachments and Documents")');
tgb.attr('target', '_blank');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Attachments and Documents
The issue with your logic was the [0] that you were putting on the tgb. [0] on a jQuery object breaks the element out of the jQuery object and returns the native Element. There are various reasons why you would want to do this, such as if you wanted to access element properties and you don't want to go through the jQuery prop() or attr() method.
However in your case, you are trying to use the attr() method off of tgb. However, attr() is a jQuery method. Since you broke the element out of the jQuery object, this will not work.
Rather than turning the tgb back into a jQuery object, simply take off the [0]. This fixes your issue, and removes the need to create another jQuery object which, give the snippet you provided, is unnecessary work.
Optionally, if you do want it to be a native Element you could just set the attribute directly.
var tgb = $(...)[0];
tgb.setAttribute('href', newValue);
//or
tgb.href = newValue;

Use a jQuery Selector as a Variable

I am creating a variable that stores an elements ID in the variable. I could write it like this:
var webappData = document.getElementById('web-app-data');
If I wanted to do the same using jQuery I think I would write it like this:
var webappData = $('#web-app-data');
However, when I try that it doesn't work. (Script throws an error because the variable isn't selecting the div with that Id.)
How would I use jQuery to select an element and store it in a variable?
document.getElementById('web-app-data') isn't the same as $('#web-app-data'). The later returns jQuery object, which is kind of an array of HTMLElement objects (only one in your case).
If you want to get HTMLElement, use $('#web-app-data')[0]. Check:
document.getElementById('web-app-data') === $('#web-app-data')[0]; // true
It's ok.. Maybe something else is wrong in your code..
Example:
<div id="web-app-data">
Hello
</div>
<script type='text/javascript'>
var webappData = $('#web-app-data');
alert(webappData.text()); // Hello
</script>
Fiddle
Above code should work just fine. Your problem might be, that jQuery doesn't find any corresponding elements from the DOM since the element has been removed or hasn't been loaded there yet. If you try to
console.log($('#web-app-data'));
that variable, you can check if jQuery actually found anything. jQuery object should have lenght of (atleast) one if corrensponding element is indeed in DOM atm.
That will work and you use just like it was the full JQuery selector.
var elm = $('#webappData');
if (elm.hasClass('someClass')) elm.removeClass('someClass');
return;

I want to animate the appendChild() , so that it fades in

Hi I want to add fade in effect , to a chrome plugin which shows up using appendChild().
I want something like,
document.body.appendChild(div).fadeIn(1000);
Is their a way to do so ?
the fadeIn() method is provided by jQuery - Assuming div is a dom element reference, you need to get the jQuery wrapper for it and then call fadeIn
var div = document.createElement('div');
...
document.body.appendChild(div);
$(div).hide().fadeIn(1000);
it can even be written as
var div = document.createElement('div');
...
$(div).hide().appendTo(document.body).fadeIn(1000);
fadeIn() is a jQuery method, not a DOM method so you need to call it on a jQuery object, not a DOM object. In addition, you probably want to hide the element before appending it like this:
// assumes you already have an element to append in a variable named div
div.style.display = "none";
document.body.appendChild(div);
$(div).fadeIn(1000);
Or, using more jQuery, it could be like this:
$(div).hide().appendTo(document.body).fadeIn(1000);
Please try use this code
$('<div class="someelement"/>').appendTo('body');
$('.someelement').fadeIn();

How to add text to a DIV from array of DIVs

Var divs = $(".txt"); this will return a list of divs with a class txt .
I want to add text to a selected div for example :
divs[4].html("Hello World"); this with return error saying divs[4].html is not a function. why ?
When you access a jQuery object by its DOM array index, you get the HTML element, not a jQuery object, which doesn't have the html() function. Use the eq(n) selector instead:
$(".txt:eq(4)").html("Hello World");
The divs[0] is giving you a DOM reference, not a jQuery object. So, pass that to the jQuery function ($() is shorthand for jQuery()):
$(document).ready(function(){
var divs = $('.txt');
$(divs[4]).html('this one');
});
http://jsfiddle.net/userdude/unu8g/
Note as well the use of $(document).ready(), which will wait until the DOM is accessible. $(window).load() will suffice for this as well, although it may fire after onDOMReady.
The non jQuery way:
document.getElementsByClassName("txt")[4].innerHTML = "banananana!";
Just a side note: I'd suggest learning basic browser javascript before moving to libraries.
It will give you an understanding of how such libraries work and will keep you from being 'locked in' to a specific few

Why is document.getelementbyId not working in Firefox?

I can't figure out why document.getElementById is not working in Firefox:
document.getElementById("main").style.width = "100";
When I check in Firebug it says:
TypeError: document.getElementById("main") is null
Does anybody know why this is happening?
EDIT: Unfortunately, the "body" element was a bad example. I changed it to another element with an id of "main".
put your script before
</body>
Or, if you use your script in <head> you may change code:
$(document).ready(function() {
//enter code here.
});
Did you set the id of the <body> element to "body":
<body id="body" ...>
Update:
Check if the following example works for you: http://jsbin.com/uyeca/edit
Click the Output tab to see the result (which should be a DIV with width 600px).
https://developer.mozilla.org/En/DOM/Document.getElementById
Simply creating an element and
assigning an ID will not make the
element accessible by getElementById.
Instead one needs to insert the
element first into the document tree
with insertBefore or a similar method,
probably into a hidden div.
var element = document.createElement("div");
element.id = 'testqq';
var el = document.getElementById('testqq'); //
el will be null!
I had the same prob...I was trying to use "getElementById" without the main structure of the HTML page-- tag was missing.
After adding in my page it worked fine...I was working on a script that was supposed to be embeded on other sites--widget sort of thing.

Categories

Resources