Insert a whole element into another element, not just its inner HTML - javascript

I'm trying to figure out how to use jQuery to construct HTML as sanely as possible. As far as I can tell, this should produce <div><span>Alice</span></div>, but instead produces <div>[object Object]</div>:
post = $("<div>");
username = $("<span>").html("Alice");
post.append(username);
I've found that replacing the last line with post.append(username.html()) gets me closer to my goal, but it omits the <span> tags if I do it that way. How do I insert a child element with the surrounding tags, and without writing out "<span>" + username + "</span>", which seems like a novice approach to the task?
EDIT: Stupid mistake. The snippet I posted above was excessively simplified; I was really trying to do post.append(username + another_span_element) in my code. Obviously I can't append objects like that. I've changed it to post.append(username); post.append(another_span_element); and now it works fine. Durr!

Works for me: $("<div>").append($("<span>").html("Alice"))[0].outerHTML == "<div><span>Alice</span></div>"

What you're aiming for is done with the text() method:
post = $("<div>");
username = $("<span>").text("Alice");
post.append(username);
Example here.

Is there a reason for not doing:
$('<div><span>Alice</span></div>').appendTo('body');
or
var username = "Alice";
$('<div><span id="user"></span></div>').appendTo('body');
$(username).appendTo('#user');
or
var username = "Alice";
$('<div><span id="user"></span></div>').appendTo('body');
$('#user').html(username);
or
var username = "Alice";
$('<div><span id="user"></span></div>').appendTo('body');
$('#user').text(username);
or any of the other 200 options?

Related

Correct way to convert your JavaScript function into a string so it can be inserted into innerHTML

This is what I am doing: I am building a fun in house API Voting System. I am using a client side snippet insert onto page
Like this:
<script src="domain.com/api/scripts/main.js"></script>
<div id="content-wrap" id="ac1e435e-c564-48f8-9f45-338616e7a789"></div>
Now in my main .JS I do all ajax request and modify the #content-wrap with creating new elements and inserting additional JS required to run Voting System.
However big issue I am experiencing is when I write JavaScript that I need to insert into #content-wrap I am currently writing it like this:
script.innerHTML = "$(someting).on('click', funciton(){"
+ "$.ajax({type: 'post',"
+ " url: '" + base + "/api/request', data: $('form').serialize(), "
+ "success: function(response){";
As you can see that can cause lot of issues as I build on it.
What is better way to accomplish this or is there a way i can just write my script / code and do something like this.
script.innerHTML = ConvertToString(script.js) OR ConvertToString(function X);
ConvertToString is just an expression I am using to explain what I would like to do instead of what I am doing.
Thank you, I am open to any suggestions.
I also must do this in plain JavaScript or with jQuery library so any suggestions to use VueJs, AngularJS or React will be considered as future references.
Thank you again
Additional explanation:
I would like to insert into my script element JavaScript snippet. But my snippet is about 30 lines long currently and might get bigger with time so it is very difficult to code with all the + " code " on every line that I write so that it can be inserted with innerHTML into element and executed on Client end.
So I would instead like to do something like this
element.innerHTML = mysnippetcode // but with out using + "" on each line like shown above
OR
element.append(snippet)
I hope this makes it little more clear
Solution that worked for me was using back ticks to wrap my sinppet and insert it into innerHTML of the element..
Just use the function's name without the () to convert it to a string:
function foo() {
var a = 10;
var b = 20;
var c = a + b;
return c;
}
document.write(foo);
The document.write will result in this string:
function foo() { var a = 10; var b = 20; var c = a + b; return c; }
If you only want the function's body, then you could just normally remove the first and last characters of the string.
I am not entirely sure this is what you wanted, if not, please make yourself more clear.
Alternatively, you could do an eval([insert function code here]) and there would be no need to add the code to the innterHTML of the script, read up on that function if you haven't heard of it.
Or if you want to create a function from a string, you can use new Function([name] ,[function body string]) if you need arguments you have to sandwich them between the 2 parameters.
But my snippet is about 30 lines long currently and might get bigger with time > so it is very difficult to code with all the + " code " on every line that I
write
You can use template literals if you want multi-line strings in Javascript, you simply have to replace your quotes with backticks.
See this MDN page if you are interested, or even this StackOverflow answer.

Adding new lines in a textarea with javascript (ie 9)

Looked all over, but I can't find the answer. I am trying to generate JSON from some inputs and display the generated JSON in a textarea, like below. But no matter what I try, I can't get my fields to show on separate lines. Any help appreciated
var txt = "{a : 'a',\r\nb : 'b'\r\n}";
document.getElementById('eventsJSON').innerHTML = txt;
Edit: I have simplified my example to something reproducable that demonstrates my problem
You can try this replace function:
.replace(/(\r\n|\r|\n)/g, '\r\n');
It might also be a matter of using an innerText instead of a value change:
... elem.innerText + (!fields.local[i].number ? "'" : '') ...

Can't use document.getElementById().innerHTML to rewrite the original html

I am tring to add some content after the original content, but the new content will cover the original content everytime...What wrong in this case? (Sorry for my terrible english...)
var originaltext = document.getElementById("id").innerHTML;
document.getElementById("id").innerHTML = originaltext + "newtext";
One more thing,I tried to use alert to show the "originalltext", but it have nothing to show.
alert(originaltext);
your code looks ok to me. I made a jsfiddle for you just to see that it works http://jsfiddle.net/3mqsLweo/
var myElement = document.getElementById('test');
var originalText = myElement.innerHTML.toString();
myElement.innerHTML = originalText+" new text";
check that you only have one element with the id "cartzone"
A simple and fast way to do this is to concatenate the old value with the new.
document.getElementById('myid').innerHTML += " my new text here"
this problem usually occurs when the rest of your code is poorly written and contains errors or when the same ID is used several times.
I had the same problems in the past.
you have tow options:
check the rest of your code (validate)
use jQuery - I don't know how, but it works every time.

How to find and replace text in between two tags in HTML or XML document using jQuery?

I want to find and replace text in a HTML document between, say inside the <title> tags. For example,
var str = "<html><head><title>Just a title</title></head><body>Do nothing</body></html>";
var newTitle = "Updated title information";
I tried using parseXML() in jQuery (example below), but it is not working:
var doc= $($.parseXML(str));
doc.find('title').text(newTitle);
str=doc.text();
Is there a different way to find and replace text inside HTML tags? Regex or may be using replaceWith() or something similar?
I did something similar in a question earlier today using regexes:
str = str.replace(/<title>[\s\S]*?<\/title>/, '<title>' + newTitle + '<\/title>');
That should find and replace it. [\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </title>.
You can also do something like this:
var doc = $($.parseXML(str));
doc.find('title').text(newTitle);
// get your new data back to a string
str = (new XMLSerializer()).serializeToString(doc[0]);
Here is a fiddle: http://jsfiddle.net/Z89dL/1/
This would be a wonderful time to use Javascript's stristr(haystack, needle, bool) method. First, you need to get the head of the document using $('head'), then get the contents using .innerHTML.
For the sake of the answer, let's store $('head').innerHTML in a var called head. First, let's get everything before the title with stristr(head, '<title>', true), and what's after the title with stristr(head, '</title>') and store them in vars called before and after, respectively. Now, the final line is simple:
head.innerHTML = before + "<title>" + newTitle + after;

JQUERY FIND:FIRST not finding the first Paragraph?

Goal, is to extract the content for the CKEDITOR Text Editor, and then only obtain the FIRST paragraph. For some reason the bellow isn't working... Ideas?
Given the following JavaScript:
var newTitle = CKEDITOR.instances.meeting_notes.getData();
newTitle = $(newTitle).find("p:first").text();
It doesn't work because find() searches the descendants and your paragraph must be at the top level of the HTML you're searching.
For example:
alert($("<p id='one'>one</p><p id='two'>two</p>").find("p:first").attr("id"));
returns "undefined" whereas:
alert($("<p id='one'>one</p><p id='two'>two</p>").filter("p:first").attr("id"));
will output "one".
So you could use filter() if you know it's at the top level (possibly falling back to find()). Alternatively you could wrap the whole lot up in a dummy element:
alert($("<div>" + html + "</div>").find("p:first").text());
Edit: My advice? Use:
newtitle = $(newtitle).filter("p:first").text();
I am not sure if works for you, but just try putting a space before :first,
for some reasons i can't explain this works as far my experience is concerned:
The new selector for find would now be, find("p: first")
var newTitle = CKEDITOR.instances.meeting_notes.getData();
newTitle = $(newTitle).find("p :first").text();
BTW can you post some sample values of the newTitle, just curious of what it looks like!
This is completely untested, but assuming that what getData returns is a string of HTML, try this:
newTitle=$("<div>").html(newTitle).find("p:first").text();

Categories