Append HTML to HTML string in jQuery - javascript

I have a HTML string and I want to append another html string to this in some arbitrary location.
Example:
var htmlString = '<div id="insert"> <p> Hello </p> </div>'
var appendString = '<p> Goodbye </p>'
$(appendString).appendTo( $(htmlString).find('#insert') )
Obviously that doesn't work because it cannot insert directly into the string however, I do not want to convert htmlString into a jQuery object because it messes up the structure of the HTML document and I need the script tags to remain in the locations they have been inserted.
Hope that's clear enough.
EDIT:
My apologies, I think I explained my problem poorly.
I have a HTML string that includes a table and I want to append a new row to the table. My problem is that I have a number of <script> tags that I need to remain in their locations. When I convert the string into a $(string), I am then unable to return it to its original form:
var htmlString = $('body').html();
var $htmlString = $(x);
console.log($htmlString.html());
This is a Confluence page that I attempting to do this on and I have limited access to the source; most I can do is to modify what is already there.
The HTML string comes from a AJAX request of another page on Confluence and I need the scripts to remain in the same place so that my other macros will run correctly.
I have included a JS Bin example of my problem to hopefully illustrate my problem clearly.
https://jsbin.com/ruwawuzica/edit?html,js,output

You can do it like this:
var htmlString = '<div id="insert"> <p> Hello </p> </div>';
var appendString = '<p> Goodbye </p>';
var added = ($(htmlString).append($(appendString)));
$(added).appendTo('div');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
Since $(htmlString) is the element <div id="insert"></div> wrapped in jquery

Hi #MyLittleDax i guess you can do this:
var htmlString = "<div id='insert'> <p> Hello </p> </div>";
var appendString = "<p> Goodbye </p>";
//your container where you put the html
var container = $('#container');
container.empty();
container.append(htmlString);
var insert = $('#insert');
insert.append(appendString);
good luck!!!

Related

Cleanest way to create html & xml content in angularjs

I need to send HTML string inside XML to a POST REST service.
Currently I am using string concatenation to create XML's and HTML's like the following,
var html = " <div style='some style'>... append model data from the response of some services ... </div> ";
html += " <div> ... append model data from the response of some services ...</div> ";
var xml = "<?xml version='1.0' encoding='utf-8'?>";
xml += "<root><data>";
xml += "<![CDATA["+ html +"]]>";
xml += "</data></root>";
return $http.post(url,xml,{headers : {'Content-Type': 'application/atom+xml'}});
It looks really ugly as the real html content is huge. Which is the cleanest way to achieve this except string concatenation?
You can do following:
Put your html code in body tag under any specific tag like div with some id or class (I have used id)
example:
The content of the document......
... append model data from the response of some services ...
... append model data from the response of some services ...
Now in javascript you can do like below:
var html = document.getElementById("parent_div").innerHTML;
alert(html);
using above code you can use your html without writing it in JS code.
Also, you can hide this if you don't want to show it on your page.

string from json is being written as text and not as dom elements

document.getElementById("id").innerHTML = "<div>new div</div>";
writes a new div element no problem, however a string from json:
document.getElementById("id").innerHTML = jsonData.data.children[i].data.media.oembed.html;
is always written as text with quotes!
(ie: "<iframe></iframe").
yielding:
<div id="id">
"<iframe></iframe>"
</div>
and not
<div id="id">
<iframe></iframe>
</div> //as expected
I don't understand why. I want to write this string to el.innerHTML as a string without quotes so it acts like a simple element.
data from reddit.json
sample:
html: "<iframe class="embedly-embed" src="//cdn.embedly.com/widgets/media.html?src=http%3A%2F%2Fwww.youtube.com%2Fembed%2FJq9JMm9h9cA%3Ffeature%3Doembed&url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJq9JMm9h9cA&image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FJq9JMm9h9cA%2Fhqdefault.jpg&key=2aa3c4d5f3de4f5b9120b660ad850dc9&type=text%2Fhtml&schema=youtube" width="600" height="450" scrolling="no" frameborder="0" allowfullscreen></iframe>"provider_name: "YouTube"provider_url: "http://www.youtube.com/"thumbnail_height: 360thumbnail_url: "http://i.ytimg.com/vi/Jq9JMm9h9cA/hqdefault.jpg"thumbnail_width: 480title: "Good Doggy"type: "video"url: "http://www.youtube.com/watch?v=Jq9JMm9h9cA"version: "1.0"width: 600__proto__: Objecttype: "youtu.be"__proto__: Object
The html property that you are accessing is XML encoded:
"html": "<iframe class=\"embedly-embed\" src=\"https://cdn.emb......
Note the < there at the beginning.
In order to use it as HTML, you'll need to decode it. One way you can do this is to assign it to .innerHTML, retrieve it as text, and then assign it to .innerHTML again:
var el = document.getElementById("id");
el.innerHTML = jsonData.data.children[i].data.media.oembed.html;
el.innerHTML = el.textContent; // assign it for a second time
Obligatory warning: Make sure you darn well trust the source of the content you are using here. This opens your site wide up for an XSS attack if the source is untrustworthy.

regex for getting html starting tags

I want get only the starting html tags. Lets say I have html like this
<div class="some">Here is a sample text<br /><p>A paragraph here</p></div>
<ul><li>List Item</li></ul>
From the above html I want to extract this information
<div
<br
<p
<ul
<li
see I dont need ending '>' of tags
Try regex /<[a-zA-Z]+[1-6]?/g. I added the [1-6] for the header HTML tags - I think they're the only ones with numbers. If you wanted to be sure you could do /<[a-zA-Z0-9]+/g, since in HTML a < is always a tag (unless it's a comment <--), because in-line < get converted to <.
The following returns you an array of the matches with what you want from the html body.
'<div class="some">Here is a sample text<br /><p>A paragraph here</p></div><ul><li>List Item</li></ul>'.match(/<\w+/g)
How about this:
String input = "<div class=\"some\">Here is a sample text<br /><p>A paragraph here</p></div><ul><li>List Item</li></ul><6>";
Scanner scanner = new Scanner(input);
String result = "";
while( (result = scanner.findInLine("<\\w+")) !=null ){
System.out.println(result);
}

is there a javascript/jquery selector for text selected by mouse cursor?

is there a jquery selector for text that is highlighted after its dragged over by the mouse cursor? For example, I want to select text that I've typed into my textarea field, click a button, which puts <p> tags around the text I've highlighted with my mouse cursor. A non-plugin solution would be preferred, thanks.
There's a straight up javascript solution that's pretty nice... just use inputElement.selectionStart and inputElement.selectionEnd .
It's helpful to note that this is just on Dom elements, so you'll have to take your jQuery selector for your textarea and add [0] to get the element itself, ie. $("#myTextArea")[0].selectionStart.
From there you can do some string work and add in your <p> tags at the appropriate indexes.
I haven't tested this, but it should work...
var selStart = $("#myTextArea")[0].selectionStart;
var selEnd = $("#myTextArea")[0].selectionEnd;
var originalString = $("#myTextArea").val();
var segment_1 = originalString.substr(0,selStart);
var segment_2 = originalString.substr(selStart,selEnd);
var segment_3 = originalString.substr(selEnd,originalString.length);
var finalString = segment_1 + "<p>" + segment_2 + "</p>" + segment_3;
$("#myTextArea").val(finalString);
Why dont you use php for this? PHP + jQuery will help you.
Example form:
<form action="highlight.php" method="post">
My textarea:<br />
<textarea cols="10" rows="10" name="textarea"></textarea>
<input type="submit" value="Wrap <p> around" />
</form>
PHP to process the form and wrap around it:
<?php
$text = $_POST[''];
$wrap = '<p>'.$text.'</p>';
echo '<textarea cols="10" rows="10">'.$wrap.'</p>';
?>
You can remove echo $wrap, but i prefer you learn jQuery and how you can use it to execute a php script.
I Dont have that much jQuery experience to tell you how, but learn it or google "How to execute php script with jquery" and im sure you will find something =)

How can i use html tags in javascript

I wrote an ajax program.when i am getting response, at that time i will display
that content in my web page using html tags.
So how can I use html tags in javascript?
A sample data you get from server, and a sample html you want to add would make it easier for people to help you.
The basic steps are
1.Get a reference to the html node you want to put the new data in. There are multiple strategies to get reference to the node. If it has an id, it's most starightforward.
2.set innerHTML property.
eg
var node = document.getElementById("targetNode");
node.innerHTML = "<div>data</div>";
Well... Not much detail so not much of an answer...
Easy way
document.write("<body> <div> this is on my page! </div> </body>
or you can edit the innerhtml of an element to place things inside it
document.getElementById("id").innerHTML = "<div>This is inside my element with id="id" </div>"
Answers the question, no?
Instead of embedding html into javascript, you could make a bunch of predefined javascript functions and then use them outside of the script tags. For example, here's how to display a picture while still using the javascript functions.
<html>
<script type="text/javascript">
function display_message()
{
alert("This is a message.");
};
</script>
<body>
<img src="image.jpg">
<form>
<input type="button" value="Click me!" onclick="display_message()" />
</form>
</body>
</html>
I know this is an old post, but this could be helpful...
Using jquery is great way to combine html elements with script
Note: This would be used in the body, if using it in the be sure to enclose it in
$(document).ready (function(){ YOUR CODE });
// Create an object:
var url = {
link: "https://stackoverflow.com/questions/2834929/how-can-i-use-html-tags-in-javascript"
};
// Display URL object:
$('#panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//Note: the # denotes id, if you want to use a class it would be:
//$('.panel').html('<a href=' + url.link + '>' + url.link + '</a>');
//your html would be: <div id="panel"></div> or whatever you choose ie <p> and so //forth

Categories

Resources