I'm trying to read in the entire page's HTML (including the doctype) then remove a few parts of the page in order to pass it as a string via AJAX.
What I have so far is:
var page = doctype + document.documentElement.outerHTML;
This gives me the content that I want, but when I try to use jQuery's .remove() function, I'm getting undefined is not a function.
page.remove(".my-class");
I assume I'm doing something with the variable type wrong? How can I grab the full page source such that I can still manipulate it with jQuery?
You need to put the html into a jQuery object in order to manipulate it. After you do that you can use the jQuery's find method then remove method to remove elements that match .my-class:
var $page = $(doctype + document.documentElement.outerHTML);
$page.find(".my-class").remove();
After that you can get the resulting html by doing:
var htmlToSendViaAjax = $page[0].outerHTML;
If you want to manipulate HTML with jQuery, you have to call the jQuery constructor:
var page = $(doctype + document.documentElement.outerHTML);
page.remove(".my-class");
Your problem is that page is not a jQuery object and as such doesn't have methods like .remove().
If you want the outerHTML with jQuery, you need to make a jQuery selection:
$("#selector");
$(document); // for the entire document
Then you can use a solution found here to get the outerHTML of the first element in the selection (you can use a for or each loop if you do it for lots of elements:
var $selection = $("#selector")
$selection[0].outerHTML;
Related
there is a div present in my js file
<div id="myid" data="mydata"></div>
when i try to access custom attribute data with pure javascript
var data = document.getElementById('myid').getAttribute('data');
jquery alone
var data = $("#"+myid).attr('data');
above both mwthods are working properly but when i try to used the both jquery and javascript
var data = $("#"+myid).getAtrribute("data");
then is is giving error? but didn't able to get the reason ? can anyone explain please?
You are applying a dom method to a jquery object which causes error instead jquery has a method to convert the selector to the dom element .get():
$("#"+myid).get(0).getAtrribute("data");
alert($('#myid').get(0).getAttribute('data'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myid" data="mydata"></div>
As you are using a data attribute then better to use data-* attribute and jQuery has a method to get it with .data() method:
<div id="myid" data-mydata="CustomisedData"></div>
then in the jQuery:
$('#myid').data('mydata'); // will give you "CustomisedData"
Because $("#"+myid) is a jQuery instance, not HTML Element object. So you can't use DOM methods on some arbitrary object.
jQuery instance object is an array-like collection of DOM elements. It means that you can extract individual DOM element from it by index if you really need. So in your case you could do this:
$("#" + myid)[0].getAtrribute("data");
jQuery also offers dedicated method for it $.fn.get:
$("#" + myid).get(0).getAtrribute("data");
This should work:
var data = $("#"+myid)[0].getAtrribute("data");
Because to use javascript code, you need to use DOM object but jQuery uses array-like collection object.
I have a page which is generated and structured as a tree - nested DIVs, etc.. While the user views the page it is possible that some DIVs are updated on the server side and the changes are pushed to the client as JSON data, from which a DIV can be generated.
My problem is that even though I have the old DIV
var oldDiv = $('#foo');
and I have a new DIV generated by
var newDiv = generateDiv(jsonData);
I need to update the old one (both attributes and it's content) without deleting it. I was going to use the jQuery method .replaceWith() as such
oldDiv.replaceWith(newDiv);
but according to the documentation it is implemented as remove&create.
The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call.
How can I update the old DIV without removing it? Is there some nice way to do this, or do I need to do it attribute by attribute?
As you've suggested, you may need to replace the attribute values individually. However, if it reads better, you can actually pass an object to the attr method, and it will update the values you supply.
oldDiv.attr({
attr1: newDiv.attr1,
attr2: newDiv.attr2,
attr3: newDiv.attr3
});
If you wanted to loop through the attributes to build the object, you could do that like this.
var newAttributes = {};
$.each(newDiv[0].attributes, function(index, attribute){
newAttributes[attribute.name] = attribute.value;
});
oldDiv.attr(newAttributes);
It cannot be done since a div element may contain many elements. Why dont u just append the new contents into it.
You can use jquery's append() method.
$(oldDiv).append("#new_div_id");
It will be appended as a child.
If at all you want to update any <p> element, you can use the html() function to get the contents of a tag and then
old_para_contents=("p").html();
$("p").html(old_para_contents+"New contents");
I've come up with one solution so far, but if anyone comes up with a better one, I will gladly assign it as the correct one. I need to make this as clean as possible.
var oldDiv = $('#my-old-div');
var newDiv = generateDiv(data);
oldDiv.attr("id", newDiv.attr("id"));
oldDiv.attr("class", newDiv.attr("class"));
//...
oldDiv.html(newDiv.html());
Can someone explain why this doesn't change the audio file src attribute, I would think it would?
var correctAudio = document.createElement('audio');
correctAudio.setAttribute('id', 'correctAudio');
correctAudio.setAttribute('src', 'sfx/correct/3.mp3');
function playCorrect(){
var num = Math.floor((Math.random()*4)+1);
num = num.toString();
$('#correctAudio').attr('src','sfx/correct/'+num+'.mp3');
correctAudio.play();
}
playCorrect();
It only works if I call document.body.appendChild(correctAudio);
Seems as if jQuery can only access the element if it is appended to the page - is this correct or is this a jQuery bug?
It is correct behaviour. jQuery searches the document for a matching element, the element is not part of the document.
You can just wrap the existing reference to the DOM object using jQuery (rather then searching the document for a new reference to wrap):
$(correctAudio)
… but you might find you still can't play it when it isn't part of the document.
I have already found some question of this genre but the answer didn't help.
Javascript - div content without innerHTML
Javascript: Does not change the div innerHTML
I have a div called adx-title by id and i have to change the content. So i made my ajax call and i stored (i use jQuery) in a call the title i want this div to contain:
$('#adx-title').inneHTML = title;
Firebug report this ($('#adx-title').inneHTML) as undefined, and it does report so in every attempt i make to change the content of the div, which is read as an object but it doesn't have the innerHTML property. The script is loaded after i click a button so it should recognize the div as already loaded by the page. And indeed it gets the div with $('#adx-title'). it just doesn't apply the change and reports innerHTML as undefined.
Anyone has had a similar issue? Anyone can help? Thanks Agnese
You're using jQuery.
$('#adx-title').html( title );
The .innerHTML property is part of the DOM API. When you make a call to jQuery (as you're doing with the $) the result is a jQuery object, not a DOM element.
You can get the DOM element from the jQuery object like this:
var elem = $('#adx-title').get(0);
However, the jQuery .html() API wraps access to the .innerHTML property and also provides some other useful bookkeeping features. If you're using jQuery in general to manipulate the DOM, it's a good idea to use .html() and not the raw DOM API for that reason.
Try $('#adx-title').html(title);
I'm trying to make a simple image browser for TinyMCE which I am using in my CMS. As part of this I need to detect whether the user has selected an existing image, so I can display the "edit" form instead of the "choose an image form".
var selected_html = ed.selection.getContent();
var $elem = $(selected_html);
console.log($elem);
The first function returns the user selected text from the editor window as a string of HTML. I then would like to use jQuery (although plain javascript is just ok too) to check if this string contains an img tag before subsequently grabbing the src and title attributes for editing.
Now I've got as far as getting the html to turn into an object. But after this I can't manage to search it for the img element. After reading this (How to manipulate HTML within a jQuery variable?) I tried:
$elem.find('img');
But it just comes out as an "undefined" object...
I think I'm missing something fairly obvious here (it is getting late), but after an hour I still can't figure out how to grab the img tag from the selection. :(
Many thanks in advance.
Because the <img> is at the root of the jQuery object, you need to use .filter() instead of .find().
$elem.filter('img');
The .filter() method looks at the element(s) at the top level of the jQuery object, while .find() looks for elements nested in any of the top level elements.
If you're not sure beforehand where the target element will be, you could place the HTML into a wrapper <div> to search from. That way the HTML given will never be at the top.
var selected_html = ed.selection.getContent();
var $elem = $('<div>').html(selected_html);
var $img = $elem.find('img');
Try to see what is really inside your $elem variable. Just do a console.log($elem) using both Firefox and Firebug and you should be able to manage quite alright! ;)