jQuery, Html element form external file to string in jquery, how? - javascript

I am working on a project where i need to get a specific element from an external html file as a string in my jQuery.
As i understand the .get(); function cannot get a specific element (by class or ID) and the .load() can, but loads it directly into the dom of the file.
Is there another function or a way to go about this?
What i need to do is get a specific html element and replace some macros in it with data from an object and then append it to an element (multiple times.) Therefore i cannot just load it in and replace the macros afterwards.

You can .get it and then only subselect.
$.get('myfile.html', function(response) {
var inside = $(response).find('#inner-id');
// do stuff with inside...
});

Related

Best practise for update DOM after Ajax call

I want to know what's the best practise for updating DOM after an Ajax call.
For example, imagine we have a list of users and we can add a user with a form which make an Ajax call to insert the user. After the form is submitted and the user added in database, the DOM is edited to add HTML without refreshing the page (with the Ajax success event).
I see two possibility to make this :
Make an Ajax call who add the user in db and return all the DOM structure with html tag, etc.
Make an Ajax who add the user in db and return all the data of an user and create the DOM element in Javascript
What'is the best way to do it (or another way) ?
You can add elements to the DOM with document.createElement(). Then use the innerHTML property to add content to the element. Finally append the element to another with .appendChild().
There is no better way between the two options. You can either prepare your HTML structure in the backend and import the written HTML and directly append it with JavaScript or create the elements frontend in JavaScript.
Here are the main advantages to using the latter:
it's easier to debug JavaScript than PHP (PHP files targetted by AJAX calls are quite hard to debug and to maintain).
returning an object with AJAX instead of an HTML string is easier to use and more maintainable. You can have an API to handle the data. PHP only returns a JSON object.
if JavaScript handles the creation of elements, you can save those in variables. Sometimes, I find it useful to save an HTMLElement in a JavaScript variable so I can later access it to change its properties without having to go through selectors (querySelector() and others).
I would go with the second option
Make an Ajax who add the user in db and return all the data of an user and create the DOM element in Javascript
Breaking it down like so to improve on readability and maintenance
Add action to AJAX that is linked to a function on the backend, (i.e PHP, Python) that does the DB update and more.
Create the Element structures in Javascript (You can maintenance uniformity with other structures on your page). And wrap it in a function.
document.body.onload = addElement;
function addElement ($newuser) {
// create a new div element that would contain user record
var newDiv = document.createElement("div");
// and give it some content
var newContent = document.createTextNode($newuser);
// add the text node to the newly created div
newDiv.appendChild(newContent);
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("user-container");
document.body.insertBefore(newDiv, currentDiv);
}

Pass a url parameter into multiple distinct a href links via javascript

Admittedly, javascript is not my strong suit. I need to be able to append a parameter from the url into three a href links using javascript. The structure of the url will be www.mysite.com?parameter.
Currently, the links are:
https://www.acme.com/sui?bc=QOS-B20
https://www.acme.com/sui?bc=USE-BFN
https://www.acme.com/sui?bc=USP-BFN
The resulting links should be:
https://www.acme.com/sui?bc=QOS-B20&sc=parameter
https://www.acme.com/sui?bc=USE-BFN&sc=parameter
https://www.acme.com/sui?bc=USP-BFN&sc=parameter
I already have jquery loaded on the page.
I tried to follow the directions on this post: Passing an URL parameter to a href link using Javascript but it didn't work.
Thanks!
You can do it easily with jquery
$('.class-of-links-to-update').each(function(){
$(this).attr('href',$(this).attr('href')+'&'+param));
});
.class-of-links-to-update is value inside class attribute on href
<a class="class-of-links-to-update" ....
I used each function to loop through results returned by jQuery.
this represents current element in list of results and $(this) will convert element into jQuery object so we can use jQuery methods to get and set attributes of HTML element.
So just execute above JavaScript to update your results.
e.g.
function updateHrefs(param) {
$('.class-of-links-to-update').each(function(){
$(this).attr('href',$(this).attr('href')+'&'+param));
});
}
end then call the function when ever you want
e.g. on button click
$('#id-of-button').click(function(){
updateHrefs('sc=parameter');
});

get appended div id in jQuery

Is there any way I can get the id (or any other reference to) the element I've just appended using jQuery .append() ?
I'm receiving an html string with ajax and injecting in a div.
$.get(URL, args).success(function (response) {
$('#mainDiv').append(response);
});
Now I have to change something to the newly appended div (like a css property).
Please note! These solutions are not accepted, reasons are provided.
append to a temporary unique div - reason: the response contains javascript which works only if the injected html is in its environment. Calling .append will make this js run and it must be inside of mainDiv.
using a known id for the injected div - reason: the div I'm receiving in response has an id but it could be a random string and, for the moment, I need to assume I don't know it.
Perhaps anybody know a secure, reliable and consistent way to access the node I've just created in mainDiv. If .append always attach at the end, perhaps refering last node is ok: am I wrong?
You can have jQuery object reference like: var j =$(response); , and then append it : $('#mainDiv').append(j); and change its css: j.css("border":"0");

jQuery: .load() method replaces target selector content or appends to it?

I wonder if anyone knows what exactly .load() method does with data it retrieved from url?
Does it replace the target selector content with data retrieved?
OR append that data to the target selector?
Still, it seems to me that .load() method replaces (overrides) the content of the target element...
The documentation is a bit blurry:
Description: Load data from the server and place the returned HTML into the matched element.
OR
.load() sets the HTML contents of the matched element to the returned data.
It replaces the content. Agreed the documentation could be clearer, although if it were appending I'd expect that to be explicit.
Essentially, and ignoring some details, this:
$("selector").load(url);
is effectively this:
$.get(url, function(html) {
$("selector").html(html);
});
It's a bit more complex if you tell jQuery you only want to load a fragment of the returned HTML.
yes it replaces..
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.

how can i append templated data to a specific div?

I am using a jquery templating plugin and want to append the object data to the id #store but Im not sure how to do this.
Basically the data is captured using .template('playerTemp', data); but Im not sure how this can be added to $('#store').append(); ?
I must say that I'm not fimilar with the template plugin, but you can use the appendTo function:
newElements.appendTo($('#store'));
So if you get the data with: .template('playerTemp', data) as you wrote, You can append it like:
.template('playerTemp', data).appendTo($('#store'));
appendTo docs:
Description: Insert every element in the set of matched elements to the end of the target.
// This compiles the template
$("#yourTemplateID").template('playerTemp');
// This appends it to a specific element
$.tmpl("playerTemp", data).appendTo("#store");
Should be something like:
$('#store').append($(this).template('playerTemp',data));
I don't know what object the "template" is envoking so I just used "this".

Categories

Resources