Clear innerHTML of dynamically loaded elements with jQuery - javascript

Everything i have read, leads more to event handlers being added using .live(), .on(), .bind(), .delegate(), etc..
I asked a question earlier that may not be coming across correctly, so i voted to delete that one and re-ask a much simpler one, from which i can do the rest i believe.
Is there a way to clear the innerhtml of an HTML element with a predefined class, including those loaded dynamically via AJAX, etc.
So every time an ajax call puts
<div class="triggerElement">something here...</div>
or similar on the page, i need it to be emptied. I think i have explained that correctly. Just let me know if not.
EDIT
Seems to be a lot of confusion. .empty & others like it will not work. If you call
$(".omButton").empty();
from the index, then some other module loads something later via AJAX with that same class, it WILL NOT empty that. If i have the element on the page first, then call it, yes it will work....
I need something along the lines of .live or .delegate that will work for any content loaded after the fact, as i have tried .empty and .html and neither work for the content that is loaded with AJAX.
Not sure how else to explain this. Thought it was pretty simple. Sorry!
EDIT 2...
index contains empty function
$(function(){
$('.omButton').empty();
$ajax... to load "loadedContent"
});
<div class="omButton"></div>
<div id="loadedContent"></div>
ajax returns
json_encode(array('test' => '<div class="omButton">Button Text</div>'));
So now the HTML on the index is
<div id="loadedContent"><div class="omButton">Button Text</div></div>
However since the inner div was not there when the page loaded, the .empty does not effect it. I need something that i can put on the page load that "monitors" for any occurance (static or dynamic) of it and empties it.
Hopefully that helps?

Try using $.ajaxComplete() - as this is triggered after every ajax request completes
$('body').ajaxComplete(function() {
$('.triggerElement').empty();
});

Try this. .empty
$.ajax({
...
complete: function(){
$(elementSelectorForWhatYouWantEmptied).empty();
}
})
or if the element that is loaded is dynamically placed in the DOM, then you can use .live().
$(elementThatIsInDOM).on(event, elementSelectorThatIsDynamicallyAdded, function(){
$(elementSelectorForWhatYouWantEmptied).empty();
})

If you're loading content using ajax, and that content is a full on tag with content
<div class="triggerElement">something here...</div>
And you want to empty that element after it is loaded, you need to do that within the callback which gets executed when the data is loaded.
$.ajax(
....
success: function(data){
$(".omButton").empty();
});

Related

JQuery Can't Detect Result of PHP Echo

While working with JQuery and PHP, I encountered the following problem:
There is a DIV with a class of "Drag" which I use twice, once hard-coded in HTML, like this:
<div class='Drag'></div>
Subsquently, PHP generates this DIV within the same page, as follows:
echo "<div class='Drag'></div>";
The PHP code executes due to an AJAX call, so maybe this is the source of the problem?
As a result, the page contains these two DIVs. Also, there is jQuery code, as follows:
$(".Drag").draggable();
But, the jQuery code will only work for the DIV which was coded in HTML and not for the one which was generated by PHP. Why?
You need to run $(".Drag").draggable() again after the ajax request is complete.
When you first call $(".Drag").draggable() the only div that is on the page is the one that is created in html.
Either your running the javascript before the DOM is finished loading and therefore before the second div is within context OR the jQuery library isn't setup to iterate over the selector.
The code to possibly resolve your issue
$(document).ready(function() {
$('.Drag').each(function() {
$(this).draggable();
});
});

Change Text using jQuery

I have a script that is pulling in news from Yahoo on a certain subject. It renders the title of the news feed like this:
<div class="header-title">subject - Yahoo! News Search Results</div>
I would like to change this to read differently. Since this is inserted via JS I thought I could change this with jQuery.
I attempted this:
$('.header-title').text('Subject News');
that did not work, I then attempted this:
$('.header-title').empty();
$('.header-title').text('Subject News');
that also did not work.
Both of the above methods look as if they had no effect on the text.
I am not sure what to do to remove the old text and replace with my text.
Note: All of my code is inside jQuery's Document Ready IE:
$(function(){
//Code Here
});
Don't forget to put your code in DOM ready:
$(function() {
$(".header-title").text("Subject News");
});
Otherwise the code should work fine.
This solution assumes you have no access to the other script that creates the feed widget
WIthout knowing more about other script it sounds like it is asynchronous, and creates the title elements also. You could have a timed interval loop that checks for the element to exist and once it exists do the update:
function changeYahooTitle(){
var $yhooTitle=$('.header-title');
if($yhooTitle.length){
$yhooTitle.text('My New Title');
}else{
/* doesn't exist so check again in 1/10th second, will loop recursively until found*/
setTimeout(changeYahooTitle, 100);
}
}
Then on page load:
$(function(){
changeYahooTitle()
})
If you do have access to the other script it can be modified to accommodate your needs, or you can still use this solution
Try using html() instead of empty() and text()
$(document).ready(function(){
$(".header-title").html("Subject News");
});
What's probably happening:
First you're setting the text: $('.header-title').text('Subject News');
THEN ... after the data finishes the load of the Yahoo or whatever content your text gets replaced actually with the new fetched data
Change the text inside the load callback (after data is loaded) and it will work.
It doesn't work because you call the function before the element is created. If you put your function inside <script> tag after the <div> element it should work

Why is document.getElementById() returning a null value when I know the ID exists?

I'm working on some custom Javascript for a CMS template at work. I want to be able to make a certain <li> element on the page receive the class of "current" for that page only. So in the global page head I have something like this:
<script type="text/javascript">
function makeCurrent(id) {
var current = document.getElementById(id);
current.setAttribute("class", "current"); // for most browsers
current.setAttribute("className", "current"); // for ie
}
</script>
Then in each individual page <head>, I have something like this:
<script type="text/javascript">makeCurrent("undergraduate")</script>
On the page I have a nav <ul>, with something like:
<li id="undergraduate">Undergraduate Program</li>
<li id="graduate">Graduate Program</li>
etc.
When I load the page, the class is not applied. When I look in the Firebug console, it gives the error message:
current is null
(x) current.setAttribute("class", "current");
I'm still getting the hang of writing solid, raw javascript (learning backwards after jQuery, you know how it goes), but I want to write it in just JS. What idiotic newbie mistake am I making?
Thanks everyone!
If you execute the javascript before the DOM tree has finished loading, it will return null. So an idea would be to call the function all the way at the end before you close the body tag.
This is why most JavaScript libraries have support for a dom-ready event, modern browsers have this as well (domcontentloaded) however for wide browser support it's a little trickier to do it for yourself (well, not that difficult, 3 or 4 different ways I think.)
The element does not exist yet when that script is being evaluated. Put it in the body's onload handler or something instead, so it executes once the DOM is in place.
An example of how to do this without touching any markup:
function callWhenLoaded(func) {
if (window.addEventListener) {
window.addEventListener("load", func, false);
} else if (window.attachEvent) {
window.attachEvent("onload", func);
}
}
callWhenLoaded(function() { makeCurrent("undergraduate"); });
The DOM is not fully loaded if you run makeCurrent in your head. You should put that script after your <li> tags.
Your code can be optimized: you can set a class attribute directly with current.className = 'current';.
The reason is that your script is being run before the page load is complete, and therefore before the DOM is populated.
You need to make sure you only call the function after page load is complete. Do this by triggering it using document.onload() or an onload event on the body tag.
After all the technical answers have been spewed out already, I'm going to skip all those which it very well could be and go for some of the more obvious ones I've run into which have caused me to facepalm once I've realised:
Typo in the identity
The identity isn't what you think it is because it's being generated or partially generated by the web framework you're using i.e. in ASP.NET you could set the client id to "MyControl" only to find that by the time it is rendered in the client it's "Page_1$Control_0$MyControl$1"
You've prepended it with a # in one or more of the incorrect places, for instance, although you're not using jQuery in your example if the object id is MyControl, in jQuery and CSS you reference it using #MyControl, but in the actual id of the object, you didn't use #. In document.getElementById() you don't use a # like you would in jQuery and CSS, but you may have used it inadvertently.
You've set the name element in the control instead of the id.
As other people have mentioned though, it could be down to not waiting for the element to be available at the time you're referencing it.

jQuery objects don't work

When I store a jQuery object in a variable, like this:
var $myObject = $("div#comments");
...I can't use the object $myObject!
This is what I'm doing to change the html of div#comments:
$myObject.html(data);
It does nothing. I already tried this way too, this time to select an element inside div#comments:
$("div.comment", $myObject);
It doesn't work.
I just want to be able to save an element in a variable and then use it!
Note: some people don't put $ before the variable name, like this: myObject.
Are you calling it after the document is loaded?
// This will ensure that the code doesn't run until
// the document has loaded
$(function() {
var $myObject = $("div#comments");
});
(This is a shortcut for jQuery's .ready() method.)
http://api.jquery.com/ready/
As long as the document is loaded, and you have a <div> with the ID comments on the page when it loads, it should work.
Also remember that there can only be one element on the page with any given ID. Because of this, it is actually a little better (quicker) to do $("#comments"); instead of $("div#comments");.
You've only provided snippits of your code, so it is impossible to tell for sure, but the odds are that you are running the code in a <script> element that appears before the <div> element and don't do anything (such as use the ready event) to delay the execution of the code until the div exists.
The result is that you get a jQuery object which found no elements. Move the script element so it is after the div. Just before the end tag for the body is a good place.
The syntax is perfectly valid and should work. Are you dynamically appending the comments div? You should alert( $myObject.length ) to see if it's 0 or 1, if its 0 that means it's never picked up.
You may need to bind the var statement until after dom ready, window load, or your ajax callback.
Well, that syntax is perfectly fine so something else is going on. Can you show your markup? And what do you get if you add an alert($myObject.length)? And one last thing to check... are you running this inside an on-ready handler?
Ok, thanks everyone for that.
I got the solution.
I thought about the order the things were loaded in the DOM and found the solution.
The problem (with the markup) was:
<div id="comments">
<script type="text/javascript">
loadComments(params);
</script>
</div>
The code above was written by PHP!
So it executed the function as soon as the browser read the code.
I already tried to put the script on the end of the page, after the function was called. The funcion was not defined yet.
So, the funcion loadComments should be executed after the div was ready AND after the function was defined.
I wrapped the code between the tags with a .ready(), like this:
<script type="text/javascript">
$(function() {
loadComments(params);
});
</script>
It was a distraction.
Sorry everyone!
Thanks a lot.
If you have the same problem and you didn't understand what I did, ask me. XD

In jQuery, how to load ajax content after a specified element

I have the following HTML:
<div id="mydiv">
</div>
I would like to load content using jQuery so it appears after my DIV.
I've tried this:
$("#mydiv").load("/path/to/content.html");
However, this ends up with this result:
<div id="mydiv">
<p>content from file</p>
</div>
How do I get this result?
<div id="mydiv">
</div>
<p>content from file<p>
Anyone still looking for solution, I would suggest using jQuery.get() instead of .load() to load AJAX content. Then use .after() function to specify the preceding element.
Here's an example:
$.get('url.html', function(data){ // Loads content into the 'data' variable.
$('#mydiv').after(data); // Injects 'data' after the #mydiv element.
});
Use the after function.
I have one interesting but rather hard and difficult for understanding method, but using .load function. So, code:
$('#div_after').remove();
$('#mydiv').after($('<div>').load('/path/to/content.html #div_after', {
data: data, //variables to send. Useless in your case
}, function () {
$(this).children().unwrap();}
));
See, I put .remove() method to remove previously created div if you use this code more than once. You can delete first line if it will be used just once.
The idea is .after($'') creates noname div element on the page after #mydiv and .load() the html into it with callback-function
$(this).children().unwrap();
which is logically will unwrap into our noname div and "rename" it to our #div_after from loading html. It is also unnecessary if you wish using just noname div.
Cheers!
P.S. It took me a while in a project to combine all this stuff together :) I wish it would be useful.
with the after(content) function

Categories