Why jQuery html works like replaceWith when using with form? - javascript

I have form with id push-message-form and ajax call to server returns new form html to replace with. push-message-form id set on form itself, like:
<form id='push-message-form'>form content</form>
and ajax response html looks same.
From jQuery docs I understood that: html() will replaces the contents of the element, while replaceWith() replaces the actual element.
http://api.jquery.com/html/
http://api.jquery.com/replaceWith/
But I'm using
$('#push-message-form').html('<form id='push-message-form'>content</form>')
and it replaces form itself (whilst it should add another form inside current one).
The question is why html() works as replaceWith() in this case?
Update
Some answers suggests use append, sorry if it's not clear. But I don't want to append. I want to replace form with new one returned from server (keeping it's id), and replaceWith() does work just fine.
The question is why html() works too here. Since it should replace only content, but it replaces tag too.

You should be using .append() to add content to the container calling .html() is going to replace whatever is inside that container with the value you enter:
Also you're trying to append the form with the same id so you should use a class or change the id name
This:
$('#push-message-form').append('<form class="push-message-form">content</form>')
Instead of this:
$('#push-message-form').html('<form id='push-message-form'>content</form>')

.html() acutally clears the HTML inside the element & then places your new HTML in it. While you need .append() to actually make you new HTML added in the Current HTML
$('#push-message-form').append('<form id='new-form-id'>content</form>')

Related

how could I use jquery's .append to append only text and not translate to html

I have a piece of code that uses Jquery's .append method. If you put any markup inside the string it needs to append it treats the markup as valid and instead of putting it as a string it appends it as html. how could I stop this?
example.
var msg = "<script>alert()</script>"
$("div#messages").append("<br>"+msg);
this would make an alert box pop up when I want it to just put <script>alert()</script> in the div.
is there a different method I should use?
You can try using selector and text function:
$("div#messages").text('<script>alert()</script>');
This should insert only the text, not the html.
Note: as mentioned in comments, this approach will erase the entire content of that div.
In order to keep the existing content you can append to existing value like this:
//Get the existing text
var existingText = $("div#messages").text();
// Insert the already existing text plus the new one
$("div#messages").text(existingText + '<script>alert()</script>');
Or you can do it in one line:
$("div#messages").text($("div#messages").text() + '<script>alert()</script>');
Or you can use the callback mentioned in the comments by #Chris.

jquery .html() function does not give data attribute set value

i have a piece of js code that takes the html code of an element in order to send it over for saving at the server side. The html itself is dynamically generated and the elements inside it have each a data-target attribute which is also set dynamically. So before sending the string of html to be saved the .html() of jquery is used like:
var SaveString = $('#ElementID').html();
the html I get, does not include the values of the data-target attribute of each child element and instead those appear blank
data-target=""
anyone could have a clue about what's going on there?
This is because when you use the data() method to store information with an element it is stored in an object which jQuery uses internally as a cache. The information is not added to the DOM.
If you want to add the data-* attribute to the DOM, you would need to use attr() to set it, eg:
$element.attr('data-target', 'foo');
It will then be accessible when you retrieve the html() of a parent element.
Example fiddle

How to append to a variable in jquery?

I have the following code:
var golden_site = '<div id="golden_site"></div>';
$('.form_content').append(golden_site);
var lookup = '<input type="text" name="lookup" value="test">';
Why is this not working:
$(golden_site).append(lookup);
But accessing the node by id works:
$('#golden_site').append(lookup);
This $('#golden_site') selects the div with id=golden_site. While this $(golden_site) doesn't select anything.
Taken from here, you have the following ways of selecting an element using jQuery
Selecting Elements by ID
Selecting Elements by Class Name
Selecting Elements by Attribute
Selecting Elements by Compound CSS Selector
Pseudo-Selectors
The way you tried to select your div doesn't follow one of the above ways. Hence you didn't make it. While using the id you made it, since this is included in the above ways.
update
As Guffa pointed out (I didn't now it) in his comment,
The call $(golden_site) doesn't try to use the string as a selector at
all. It will create an elements from the HTML string, and actually
return that element
The code is working fine, but it doesn't do what you think.
The $(golden_site) part will create a new div element from the HTML code in the string. The lookup element will then be appended to that div. As the div is an element that you just created, it's not in the page and the lookup element that you appended to it isn't in the page either.
If you create the div element first and then append that to the page, instead of using a string in the append, then you have a reference to the div element:
var golden_site = '<div id="golden_site"></div>';
var element = $(golden_site);
$('.form_content').append(element);
Now you can append things to it:
element.append(lookup);
Because when you say
$(golden_site).append(lookup);
Actually you mean:
'<div id="golden_site"></div>'
In plain words, it's just a string, not a jQuery object that can be appended to. golden_site is just a string.
The reason is because the $() is in fact a wrapper of jQuery over the document.querySelector(). So as expected both methods should behave similar, when you do:
$("#blah").append(x);
Indeed the browser is doing this:
document.querySelector("#blah").appendChild(x);
So both methods should work as they explain here -> How query Selector works
As you can see the variable passed as argument is a string that will be used as a CSS Selector, they explain here -> CSS Selector List
I will add this graphic with some of the most common ways to select elements from the DOM, don't forget the '', courtesy from W3CSchools.

Append HTML-escaped text: jQuery

I'm used to using jQuery's .append() method to add text or HTML onto the end of a pre-existing element. I'm currently using jQuery's .text() to escape strings that could potentially contain HTML. Unfortunately, there doesn't seem to be a jQuery method that will append the results of the .text() method to an element instead of replacing its contents.
Is there a way to append, instead of replace, this escaped text to an element? Or is there a better way to escape strings containing HTML?
Thanks.
- EDIT -
A little more context: I'm building an HTML string dynamically, and so I'll need to be able to add multiple elements with escaped content programmatically.
As I have tried many ways, I think the following method is the cleanest way to add text to whatever node you want.
no stock tag needed, only plain text, which will help to avoid potential problems
$(document.createTextNode("SomePlainText")).appendTo(p);
You could create a dummy element to hold the result of .text() which can then be appended to your destination element:
$('<div/>').text('your <span>html</span> string').appendTo(...);
You could just use
$(whatever).text($(whatever).text() + whatever_you_want_to_append);
EDIT for the fiddle in my comment, try this:
for ( /* some looping parameters */ ) {
$('<li></li>') // create an li
.text(stringWithHtml) // pass it the text, as text not html
.appendTo('#thisIsWhatINeed'); // append it where you want it
}
jsFiddle

"replaceWith" not altering contents

The directive replaceWith as used in the code below only changes the target content once. If I send any other object the alert shows the proper value but not the div.
function identify (thisobj) {
alert(thisobj.value);
$("#test").replaceWith(thisobj.value);
}
The target element is shown below.
<div id="canvas_container">
<div id="test">This is a test</div>
</div>
Various objects are being passed, here, each with a different value. But though the Alert() reflects the proper content, the #Test only allows a one time change and then it retains that value forever.
You are replacing #test with your new element. It won't work again unless the element you replace it with also matches that selector.
From the jQuery docs:
The .replaceWith() method removes content from the DOM and inserts new
content in its place with a single call.
Assuming you want to keep the #test element, you can use the html method to replace the contents of it, rather than the element itself.
.replaceWith() substitutes an entire DOM node; you should be using .html(thisobj.value) or .text(thisobj.value)
You have misunderstood the use of replaceWith: it replaces the element you call it on, so after the first use, there is no element #test anymore.
You want text or maybe html:
$("#test").text(thisobj.value);
If your value contains html, use:
$("#test").html(thisobj.value);
replaceWith removes the #test element and replaces it with what you set (thisobj.value).
To replace an element's content, use .html() (or .text()).
function identify (thisobj) {
alert(thisobj.value);
$("#test").html(thisobj.value);
}
replaceWith will replace the entire element, to replace the content within #test, use:
$("#test").html(thisobj.value);
Have you looked into jQuery's text() function? If not, http://api.jquery.com/text/
It may help with replacing text

Categories

Resources