How to .append text to a div using jQuery? - javascript

I'm trying to append a piece of text to a div using jQuery. I try to do this using the following code:
<html><head></head><body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#sendButton").click(function(){
$("#conversation").append("<P>This is a message");
});
});
</script>
<div class="conversation"><p>some message</div>
<form><input type="button" id="sendButton" value="Send Message"></form>
</body></html>
Seeing the multitude of tutorials on the subject it seems to be such a simple thing to do, but I can't seem to figure out what I'm doing wrong here. Any help would be greatly appreciated.

You need to use class selector, As #conversation referes to element with id conversation
$(".conversation").append("<P>aergerag");
Fiddle DEMO
EDIT
You should look at this To Close or Not To Close Tags in HTML5 and a good question Closing tags in HTML5

replace # with . in your selector (conversation is a CLASS)
$(".conversation").append("<P>aergerag");

I am not any good at jQuery but from one of my projects I had to simply target the div with html as:
var someData = "This is a message";
$("#conversation").html(someData);
If some contents exists before this, then you can retrieve them, concatenate, and write it back into the target div.

Related

Can you switch html pages inside others using js?

https://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_image
this is about changing html content with js, but it is about images. is it possible to do something like this too, so the same but doing it with a new html file so that you can switch pages inside a page?
So the plan is to replace the html underneath (with id="id") by another html file using js.
document.getElementById("id").src = "otherfile.html";
<html>
<body>
hey guys! here is my html page. If you click underneath, content will be changed.
<html id="id">
<body>
here is the text that will change if id="id" will be changed by a different html file
</body>
</html>
</body>
</html>
Of course, I know that this won't work.
But is there a way to archieve this?
Thank you if you are reading and trynna answer my post, I understand if it's a messy and shitty question so shoutout to you.
How about changing the contents of a div instead the whole HTML? Via jQuery.
<div id="dynamic-html">
here is the text that will change if id="id" will be changed by a different html file
</div>
$( "#btnChangeHTML" ).click(function() {
$( "#dynamic-html" ).html("<div class='myclass'>This is the custom HTML</div>");
});
Here's a fiddle:
https://jsfiddle.net/u8xsker2/2/
Read about iframe. Perhaps it is what you want.

How to find active tag formats using jQuery?

I have a situation with sample code as follows:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>
<h1>The header</h1>
<div>
matter ia always matter matter ia <strong>bold matter</strong> matter matter <em>italics matter</em>matter ia <em><strong>bold italics matter</strong></em>lways matter
</div>
</p>
</body>
</html>
I am just trying to retrieve the specific tags like body->p->div->em->strong when I click on "bold italics matter" using jQuery. Is there any standard method to retrieve as per the click event?
If you wan to get the tag name of the element which is clicked, then you can use:
$('*').click(function(e) {
e.stopPropagation();
console.log($(this).prop('tagName'));
});
Fiddle Demo
I'm not completely sure about what you are trying to accomplish. If you are trying to retrieve the tag itself that the text is contained in, i would recommend that you put a <span> tag in around the the text in question and do an onclick="function()" or simply put the onclick right on the <strong> tag.
As far the the JQuery/Javascript goes, if you want to retrieve the content, it looks like
var foo = document.getElementById.innerHTMl("id");
However, this requires you to have an id in your tags which is probably the best, if not
'standard' method of retrieving the content that is within the tag.
After reading your comments, i am editing this post:
The best way to get the parent elements is to use the JQUery .parent() function. I'd imagine that you would just recursively state something like this:
var foo = $("nameofelement").parent();
I hope this is more of what your looking for.
Thanks for contributing everybody. At last I made it myself with the following code.
$(document.body).click(function(e){
var Tags=[], Target=e.target, stat_msg="";
Tags.push(Target.tagName);
while($(Target).parent().get(0).tagName!=="BODY")
{
Tags.push($(Target).parent().get(0).tagName);
Target=$(Target).parent();
}
Tags.push("BODY");
for(i=Tags.length;i>0;i--)
stat_msg=stat_msg+Tags[i-1]+" ";
alert(stat_msg);
});

Newbie to jQuery and get function

I am completely new to jQuery. I can't find any good documentation on the get function and was wondering if I could get some help.
I have an HTML page called me.html with just a single div called me. I want to use the following page to get the contents within the div. Even a google in the right direction would help. Thanks so much
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="data.js"></script>
</head>
<body>
<form id="form" runat="server">
<div>
<div id="me">
</div>
</div>
</form>
</body>
</html>
you don't need to use get(). This simple script should do it
<script>
var contentsOfMe = $('#me').html();
</script>
get is used for loading data from an url. You seem to be wanting to get the contents of a div
as in $("#me").text()
What about using the great documentation provided at http://api.jquery.com/jQuery.get/
EDIT. If you want to just get the text, use var myText=$('#me').html();, and if the html, use var myHtml=$('#me').html();
You will find the documentation for the function get here : http://api.jquery.com/jQuery.get/
But get is to perform an ajax request get on your server so I don't think that's what you need.
In jquery, most of the time you will "select" an element using jquery selector : $("#id")
This will select $(), this will say you are selecting an element using his id $("#name_of_the_id").
Then, you will have an object which will represent the selected element.
If you want to get all the html inside this element do :
function getHtmlFromElementId(id)
{
var element = $("#" + id);
var html = element.html();
return html;
}
Printing the return of this function will print all html code inside the element selected.
If you are seaching for a good tutorial on jquery, the w3schools' one is really good:
http://www.w3schools.com/jquery/jquery_examples.asp

Dynamically Written script not functioning

I have been bashing my head against a wall for about 4 hours now trying to figure out why this wont work. I have a program that needs to dynamically write code depending on the number of results from an SQL query.
I am using a jquery lightbox called EasyBox. When it is hard-coded like this, it works:
<body id="body" onload="bodyLoaded()">
<a id="link" href="#test" title="Snowflake" rel="lightbox">Hello</a>
<div id="test" style="display:none; width:320px; height:240px">
<p>Test Content</p>
</div>
<script type="text/javascript">
function bodyLoaded(){
$('#link').attr('onclick', 'logText("Hello")');
}
function logText(message){
console.log(message);
}
</script>
However, when I have the link written dynamically like this, the EasyBox popup does not fire.
<body id="body" onload="bodyLoaded()">
<div id="test" style="display:none; width:320px; height:240px">
<p>Test Content</p>
</div>
<script type="text/javascript">
function bodyLoaded(){
document.getElementById('body').innerHTML+="<a id='link' href='#test' rel='lightbox'>Hello</a>";
$('#link').attr('onclick', 'logText("Hello")');
}
function logText(message){
console.log(message);
}
</script>
Any ideas why this would work? I am pulling my hair out here!
I don't understand why you're not just using jQuery for all of this.
$(function(){
$('#body').prepend("<a id='link' href='#test' rel='lightbox'>Hello</a>");
$('#link').click(function(){
alert("Hello");
});
});
If the .click() doesn't work, you could also try .live(). Both worked for me in jsfiddle(http://jsfiddle.net/LZxrL/ and http://jsfiddle.net/LZxrL/1/).
Also, why does everyone keep saying there is no element with id='body' when the body element itself has the id of 'body.' Clearly, he wants to add a link to the body.
EDIT: I just read your comment on another post about the issue being the lightbox, not the click event. That DOES change things. I'm not familiar enough with that plugin to comment authoritatively, but I would suspect that the plugin looks for rel="lightbox" when the page loads and any elements added afterward won't be caught. Most plugins have a manual method, something like:
$('#link').lightbox();
I'm not seeing where you are loading the dynamic tags in your script. bodyLoaded() function is looking for anything with id='body' and in your second block of code I don't see any with that id tag.

Add button after script tag

I have a javascript that I want my users to be able to put on their sites. In this javascript, I want to generate a simple button, that is located exactly where the javascript has been pasted into the site. How can I do this? It would be simple if I could give my <script> tag an id and then just getting the element with the specific ID and appending after it, but I can't.
For example if I have something like this:
<body>
<p>test para</p>
<p>test para</p><p>test para</p><p>test para</p>
<p>test para</p>
<div>test div</div>
<script src="embed.js" type="text/javascript"></script>
<div>last div</div>
</body>
I want my button to be placed right between test div and last div (before or after the script tag, it doesn't matter). Can I do this?
Could you just use after -
$("div:contains('test div')").after('<input type="button"/>');
This would obviously be better if you could give the 'div' an id or a class rather than finding it by the text it contains.
jQuery can find a script tag using -
$("script[src='embed.js']").after('<input type="button"/>')
Demo - http://jsfiddle.net/7GPx7/1
embedding JavaScript something you may want to consider is your visitors may not have jQuery enabled on their sites, so you could bloat the call by loading jQuery or construct your requirement in pure JavaScript.
The embed snippet for your visitors
<script id="eduard_luca" src="http://cdn.example.com/embed.js" type="text/javascript"></script>
embed.js
var element = document.createElement('a');
element.setAttribute('href','http://google.com');
element.innerHTML = 'Click Me';
document.getElementById("eduard_luca").appendChild(element);
I Hope this help you with your project.

Categories