How to set outerHTML with jQuery - javascript

I have a UserControl. Ex:
<div id="divItem">
some html
</div>
The ajax request return new html of this UC from server. Ex:
<div id="divItem">
new html
</div>
I want to replace the old html by the new one. How could I do that. Thanks.

If you also return the div divItem
$("#divItem").replaceWith("NEW HTML");
Put the new HTML on the spot or replace the innerHTML, since they got the same container:
$("#divItem").html($("NEW HTML").html());
If you dont return the div divItem
Just put the new html:
$("#divItem").html("NEW HTML");

I guess replaceWith is what you search.
$('#divItem').replaceWith(serverResponse);

Placing data from AJAX calls into a DOM element can be done using .load().
$('#divItem').load('somePage.html');

If you want to replace 1 item with multiple items. You can try:
var item_1 = $('<div>').text('item 1');
var item_2 = $('<div>').text('item 2');
var item_3 = $('<div>').text('item 3');
// 1/.
// dont' use this way because it's hard to read
$('#divItem').prop('outerHTML', item_1.prop('outerHTML') + item_2.prop('outerHTML') + item_3.prop('outerHTML'));
// 2/.
// dont' use this way because it's same to the first's
$('#divItem')[0].outerHTML = item_1.prop('outerHTML') + item_2.prop('outerHTML') + item_3.prop('outerHTML');
// 3/.
// if you use this way, how can we continue replace "#divItem" with "item_2"?
var obj = $('#divItem').replaceWith(item_1);
// "replaceWith" returns an object which was replaced with "item_1"
// there is no way to continue with "item_2" and "item_3"
// sure, if you DON'T want to write a new line
item_1.after(item_2);
// or
item_2.insertAfter(item_1);
// 4/.
// if we write this, the result should be: "item 3item 2item 1"
$('#divItem').after(item_1).after(item_2).after(item_3);
// so, the correct **inline** solution should be:
$('#divItem').after(item_3).after(item_2).after(item_1).remove();

You just need
$('#divItem').html('new html');
This just replaces the div's innerHTML: http://api.jquery.com/html/

Related

Change location.href with jQuery

I need to change the location.href of some URLs on my site. These are product cards and they do not contain "a" (which would make this a lot easier).
Here is the HTML:
<div class="product-card " onclick="location.href='https://www.google.com'">
I mean it is pretty simple, but I just cannot get it to work. Did not find any results from Google without this type of results, all of which contain the "a":
$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')
Any ideas on how to get this to work with jQuery (or simple JS)?
I cannot change the code itself unfortunaltely, I can just manipulate it with jQuery and JS.
To change the onClick for all the class='product-card', you can do something like this:
// All the links
const links = document.getElementsByClassName('product-card');
// Loop over them
Array.prototype.forEach.call(links, function(el) {
// Set new onClick
el.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
});
<div class="product-card " onclick="location.href='https://www.google.com'">Test</div>
Will produce the following DOM:
<div class="product-card " onclick="location.href = 'http://www.live.com/'">Test</div>
Another option, is to loop over each <div> and check if something like google.com is present in the onClick, if so, we can safely change it without altering any other divs with the same class like so:
// All the divs (or any other element)
const allDivs = document.getElementsByTagName('div');
// For each
Array.from(allDivs).forEach(function(div) {
// If the 'onClick' contains 'google.com', lets change
const oc = div.getAttributeNode('onclick');
if (oc && oc.nodeValue.includes('google.com')) {
// Change onClick
div.setAttribute("onClick", "location.href = 'http://www.live.com/'" );
}
});
<div class="product-card" onclick="location.href='https://www.google.com'">Change me</div>
<div class="product-card">Don't touch me!</div>

Displaying text onclicking href [duplicate]

I have an h1 with id of toptitle that is dynamically created, and I am not able to change the HTML.
It will have a different title depends on a page. Now when it is Profile, I want to change it to New word with jQuery.
<h1 id="toptitle">Profile</h1> // Changing only when it is Profile
// to
<h1 id="toptitle">New word</h1>
Note: If the text is Profile, then change it to New word.
This should work fine (using .text():
$("#toptitle").text("New word");
Something like this should do the trick:
$(document).ready(function() {
$('#toptitle').text(function(i, oldText) {
return oldText === 'Profil' ? 'New word' : oldText;
});
});
This only replaces the content when it is Profil. See text in the jQuery API.
Something like this should work
var text = $('#toptitle').text();
if (text == 'Profil'){
$('#toptitle').text('New Word');
}
Could do it with :contains() selector as well:
$('#toptitle:contains("Profil")').text("New word");
example: http://jsfiddle.net/niklasvh/xPRzr/
Cleanest
Try this for a clean approach.
var $toptitle = $('#toptitle');
if ( $toptitle.text() == 'Profile' ) // No {} brackets necessary if it's just one line.
$toptitle.text('New Word');
$('#toptitle').html('New world');
or
$('#toptitle').text('New world');
Pretty straight forward to do:
$(function() {
$('#toptitle').html('New word');
});
The html function accepts html as well, but its straight forward for replacing text.
*In my case i have stored the new Value in the var altText
$('#toptitle').text(altText);
*
And it Worked

Targetting and Changing HTML content using jQuery

I'm trying to change the "10" in the HTML below using jQuery:
<div id="ingredients">
<h2>Ingredients</h2>
<h4>Sugar: <span class="sugar">10</span></h4>
Here have been the iterations that I've gone through that have been unsuccessful:
$(document).ready(function() {
$('#ingredients.sugar').html("5");
});
and
$(document).ready(function() {
$('span[class=sugar]').html("5");
});
In addition, how would I store the value of "10" in a variable? I'm trying to do this:
var $sugar = $('#ingredients.sugar').html();
Would that work?
Thanks!
Henry
Try:
$(document).ready(function() {
$('#ingredients .sugar').html("5");
});
Notice the space between; this says look for a .sugar child from the #ingredients parent. You should also be able to do:
var val = $('#ingredients .sugar').html();
You have missed space in your selector, this will work:
$('#ingredients .sugar').html("5");
Here's a version with a simplified selector (don't need #ingredients), factory caching and update without using quotes (5 works fine).
// Document ready
$(function () {
var $sugar = $( '.sugar' ), // Cache jQuery factory
originalValue = $sugar.html(); // Cache original value
// Update value
$sugar.html( 5 );
});

Special HTML characters injected with JS

I have a button (named Benjamin):
<input type="submit" name="btn_submit" value="Next →" />
And on a click event it says 'Loading' and does cool stuff. However, if there is a problem, I want it to change back to its original text while displaying the error message elsewhere.
$('input[name=btn_submit]').click(function() {
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val('Next →');
return false;
});
Somehow, the literal text → is applied to the button, rather than the cool →. How do I fix this?
Html is evaluated with different rules that JavaScript is. Html entities only parsed by the html parser. Either use the unicode literal, like so:
$(this).val('Next \u2192');
Or better, keep track of the original value and then set it back:
var initalButtonValue = $(this).val();
$(this).val('Loading');
// Stuff
$(this).val(initialButtonValue);
Or perhaps even better, use HTML data attributes to store the states.
<input type="submit" name="btn_submit" value="Next →" data-normal-value='Next →' data-loading-value='Loading...' />
Then:
// Set to loading
$(this).val($(this).data("loading-value"));
// and back to normal
$(this).val($(this).data("normal-value"));
Put the actual → character in there instead of a HTML entity. Using an entity only works if you set HTML content - and form values are not HTML at all.
When using it inside <input value="..."> it only works because in this case the entity is replaced while the HTML is parsed, so the value gets the actual character.
How about storing the value of the element with $.data() and retrieving it later:
$('input[name=btn_submit]').click(function() {
$.data(this, 'value', this.value);
$(this).val('Loading');
// Logicy Stuff...
// Error?
$(this).val($.data(this, 'value'));
return false;
});
Here is a demo: http://jsfiddle.net/39thm/ (the setTimeout is just for demonstration)
Docs for $.data(): http://api.jquery.com/jquery.data
Also you are using thr $(this) selector more than once, if you use it a bunch then it's a good idea to cache the selection:
$('input[name=btn_submit]').click(function() {
var $this = $(this);
$.data(this, 'value', this.value);
$this.val('Loading');
// Logicy Stuff...
// Error?
$this.val($.data(this, 'value'));
return false;
});
if you know the code for the character, you can add it to a JavaScript string with .fromCharCode():
var s = "hello " + String.fromCharCode(1023); // just a made-up number
You can also embed characters in JavaScript strings if you know their hex code:
var s = "string \u1023 string";
$("input[name='btn_submit']").click(function() {
var elem = $(this);
elem.data( "orgText", elem.val() ).val('Loading');
window.setTimeout(
function(){
elem.val( elem.data("orgText") );
}, 1000 );
return false;
});​
jsFiddle

how to get outerHTML with jquery in order to have it cross-browser

I found a response in a jquery forum and they made a function to do this but the result is not the same.
Here is an example that I created for an image button:
var buttonField = $('<input type="image" />');
buttonField.attr('id', 'butonFshi' + lastsel);
buttonField.val('Fshi');
buttonField.attr('src', 'images/square-icon.png');
if (disabled)
buttonField.attr("disabled", "disabled");
buttonField.val('Fshi');
if (onblur !== undefined)
buttonField.focusout(function () { onblur(); });
buttonField.mouseover(function () { ndryshoImazhin(1, lastsel.toString()); });
buttonField.mouseout(function () { ndryshoImazhin(0, lastsel.toString()); });
buttonField.click(function () { fshiClicked(lastsel.toString()); });
And I have this situation:
buttonField[0].outerHTML = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
instead the outer function I found gives buttonField.outer() = <INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image>
The function is:
$.fn.outer = function(val){
if(val){
$(val).insertBefore(this);
$(this).remove();
}
else{ return $("<div>").append($(this).clone()).html(); }
}
so like this I loose the handlers that I inserted.
Is there anyway to get the outerHTML with jquery in order to have it cross-browser without loosing the handlers ?!
You don't need convert it to text first (which is what disconnects it from the handlers, only DOM nodes and other specific JavaScript objects can have events). Just insert the newly created/modified node directly, e.g.
$('#old-button').after(buttonField).remove();`
after returns the previous jQuery collection so the remove gets rid of the existing element, not the new one.
Try this one:
var html_text = `<INPUT id=butonFshi1 value=Fshi src="images/square-icon.png" type=image jQuery15205073038169030395="44">`
buttonField[0].html(html_text);
:)
Check out the jQuery plugin from https://github.com/darlesson/jquery-outerhtml. With this jQuery plugin you can get the outerHTML from the first matched element, replace a set of elements and manipulate the result in a callback function.
Consider the following HTML:
<span>My example</span>
Consider the following call:
var span = $("span").outerHTML();
The variable span is equal <span>My example</span>.
In the link above you can find more example in how to use .outerHTML() plug-in.
This should work fine:
var outer = buttonField.parent().html();

Categories

Resources