Jquery html() to div doesn't work - javascript

..I suppose because the html has script tags :-/
<script type="text/javascript">
$(document).ready(function() {
$('.ad_slot').html('<scr'+'ipt type="text/javascript"><!-- amazon_ad_tag = "xxxxxxxx-xx"; amazon_ad_width = "160"; amazon_ad_height = "600"; //--></scr'+'ipt>');
});
</script>
<div class="ad_slot"></div>
without the script tags the html displays fine. Is there any way to make this work with the tags included?
I need to generate a full js code using js for a project I'm working on.
I've also added the code to jsFiddle http://jsfiddle.net/c68wu/ although I'm not sure if scripts will show in the result window.

Script tags are going to be stripped out if you attempt to add them with html. Use
jQuery.getScript() instead.

Try to escape slash in the closing script tag:
$('.ad_slot').html('...<\/script>');

You'll need to escape the forward slashes:
$('.ad_slot').html('<scr'+'ipt type="text\/javascript"><!-- amazon_ad_tag = "xxxxxxxx-xx"; amazon_ad_width = "160"; amazon_ad_height = "600"; \/\/--><\/scr'+'ipt>');
Or this:
$('.ad_slot').html('<script type="text/javascript">amazon_ad_tag = "xxxxxxxx-xx"; amazon_ad_width = "160"; amazon_ad_height = "600";</script>');
I removed the HTML comment tags and the + in script tags. Oh yeah, and I removed the escaping on the slashes...not needed.
Also, you may want to look at when your script to generate the ads is being loaded and run. I suspect it's run before and never sees this code.

Related

javascript set variable from .text method

I'm new in javascript development and I want to ask how to set variable from text method.
Example: in this code have a text method
$('.phone').text(theRestaurant.phone);
$('.location').text(theRestaurant.location);
$('.info').text(theRestaurant.info);
in the Html file, when I create any class from these will print the value from JSON file.
Example :
<div class='phone'></div>
Output: (000)000-9999
source code:
<div class='phone'>(000)000-9999</div>
I try to set this in variable but it doesn't work.
My try:
var phone = theRestaurant.phone
I want to set it in variable because I need to put it inside href value like so:
<script>
var phone = 'tel:' + phone
document.getElementById("phone").href = phone;
</script>
I hope everything clear. and If have an other solution please tell about it.
Thanks
Have you wrapped your jQuery code in a document.ready() wrapper?
If not, then the javascript might run before the page has had time to create the elements in the DOM, and nothing will work.
<script>
$(document).ready(function(){
//all javascript/jQuery code goes in here
});
</script>
Also, see my comment above about mixing up "ByClassName" and "ByID"
Answer came from #itsgoingdown
this code in main javascript file:
var phone=document.getElementById('phone').innerHTML; document.getElementsByClassName("phone")[0].href = phone;

Using regexes to modify the text of html (with javascript)

I want to modify the text in a html file using javascript in an android webview.
Essentially, I want to do what android Linkify does to text, but I don't want to do it with java code, because I feel like that might delay the webview rendering the html (if I parse the text before sending it to the webview).
So, for example a piece of html like this:
<html>
<body>
google.com <!--these two shouldn't be linked-->
akhilcherian#gmail.com <!--these two shouldn't be linked-->
<p>www.google.com</p> <!--this should be linked-->
<p>102-232-2312 2032-122-332 </p><!-- should be linked as numbers-->
</body>
</html>
Should become this:
<html>
<body>
google.com
akhilcherian#gmail.com
<p>www.google.com</p>
<p>102-232-2312 <a href="tel:2032-122-332>2032-122-332</a> </p>
</body>
</html>
I already have the regexes to convert numbers and email ids to links, and they're working well enough. What I want to ensure is that I don't link anything that's already within tags. I've removed anchor tags, so they're not an issue, but I also need to avoid linking things like this:
<div width="1000"> <!-- Don't want this '1000' to be linked (but I do want other 4 digit numbers to be)-->
So for example if my regex for links is:
var replacePattern1 = /((https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim
How do I make sure that it's not within < and >? (Answers using javascript would be appreciated, but if you feel like this is a stupid way of doing it, please let me know about alternatives).
If you're answering with javascript, this question can essentially be shortened to:
How do I write a regex in javascript to search for patterns which are not surrounded by '<' '>' tags
So if you use JS than mean is client side, your DOM page have free access of all objects of your page coef events.
May be in this step you dont need to use a regex just using DOM.
jquery lib can easy update DOM object.
in your step you want only tag.
So i suggest :
//using jquery
$("p").each(function(){
console.log($(this))
});
//js
var paras = document.getElementsByTagName("p");
for(p in paras){
console.log(paras[p])
}
As i tell you the deal is manipulate the DOM so example with you step dunno if exactly what you try to get :
var paras = document.getElementsByTagName("p");
var hrefs = [];
//what you want to replace in the loop of p
var json_urls = {"links":["http://", "tel:"]};
for(p in paras){
//copy of text content of your p
var text_cp = paras[p].textContent;
//delete the p[i] content
paras[p].textContent = "";
//create element dom a
hrefs[p] = document.createElement("a");
//i add attribute id with some affectation unique
hrefs[p].id = "_" + p;
//add attribute href to a with some affectation replace + content
hrefs[p].href = json_urls.links[p] + text_cp;
hrefs[p].textContent = text_cp;
paras[p].appendChild(hrefs[p]);
}

how to remove bug character in html using jquery

I have a bug in my code and i try to remove it using jquery.
Some code:
<div id="content">
s
<div class="breadcrumb">
<h1>Test and etc</h1> etc etc....
I want to use jquery to remove the s (if exist...in some cases not)
I've tried
var cont = $('#content').html();
$('#content').html(cont.replace('/s\s(.*)/','$1'));
Seams that the code above is not working...some sugestions ?
Don't use a regex to remove a textnode by running a replace on the HTML, target the textnode directly
var content = document.getElementById('content'),
child = content.firstChild;
if (child.nodeType === 3) { // if textNode
content.removeChild(child);
}
FIDDLE
You do need to call the code when the DOM is ready. And remove the quotes.
$(document).ready(function(){
var cont = $('#content').html();
$('#content').html(cont.replace(/s\s(.*)/,'$1'));
});
Fiddle : http://jsfiddle.net/anj1x7xe/
I don't understand, why won't you remove it directly from the HTML source?
Is the code automatically generated (aka you didn't manually write that 's' there)? Because if it is, I strongly suggest you correct the bug itself. What you're trying to do is covering up a bug, not fixing it. It's good practice to get to the source of a bug and fix it.
Alas, if you really want to do this: You need to specify when your script is called. Most likely, you want it put into the $(document).ready() event.
$(document).ready(function(){
var cont = $('#content').html();
$('#content').html(cont.replace('/s\s(.*)/','$1'));
});

Deleting and inserting Code in a DIV via jQuery

I know this has been adressed before, but I can't seem to get it working for me.
I am trying to create a football pitch with editable players via HTML/JavaScript/jQuery.
I can produce the field the first time when loading the page without any problems. The code looks like this:
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2);
</script></div>
appBuilder() looks like this:
var appBuilder = function (team1, team2) {
team1.Display();
team2.Display(); }
It simply creates the players on the pitch for both teams. As it does. I now want to push an input-button to call a function appUpdate(), which deletes the content of #pitch and puts the appBuilder()-part in again as to renew it (if I changed or added players):
var appUpdate = function () {
var newContent = "<script type='text/javascript'>appBuilder(team1, team2);</script>";
var updateItem = $('#pitch');
updateItem.empty();
updateItem.append(newContent);}
Here is what drives me nuts: It seems to work just fine up to and including the empty()-function. So the code has to be fine.
But when I try to append newContent to the #pitch-DIV, the programm seems to completely delete everything inside <head> and <body> it recreates a clean html-file (with empty html-, head-, body-tags) and inserts my players inside <body>.
Any ideas as to why it is doing that?
Thanks in advance!
UPADTE: The solution was a rookie mistake (which is fitting, since I'm a rookie). The Team.Display()-method was trying to do a document.write() call. As I learned: If you call document.write once the document is fully loaded, it will delete your site. Thanks to jfriend for the solution! :)
If you call document.write() AFTER the document has finished loading, then it will clear the current document and create a new empty one.
What you need to do is use DOM insertion operations rather than document.write() to add/change content in the DOM once the document has already loaded.
My guess is that the .Display() method is using document.write() and you need to change the way it works to insert content into a parent node rather than write it into the current position.
Some ways to insert content:
var newNode = document.createElement("div");
node.appendChild(newNode);
node.innerHTML = "<div>My Content</div>";
Or, if you're using jQuery, you can use it's wrappers for this:
obj.append("<div>My Content</div>");
obj.html("<div>My Content</div>");
.html() would empty and fill the div at once. Have you tried that ?
updateItem.html(newContent);
I proposed a JQuery replacement for your code that does what you want, ion the style of your own typing.
Note that I kept the .html() call to mimic your "empty()" function, but it is not necessary. Simply put he code in the append, straight into the html() et get rid of the extra unnecessary remaing bit of code.
My code replacement, as a 100% functioning .html file. Hope it helps, cheers.
<html>
<header>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var appBuilder = function (team1, team2) {
//team1.Display();
//team2.Display();
}
var team1, team2;
</script>
</header>
<body>
<div id="pitch" class="updateAble">
<script type="text/javascript">
appBuilder(team1, team2); // Original code to be updated
</script>
</div>
<script>
var appUpdate = function () {
$("#pitch").html("<!-- Old javscript code has been flushed -->").append($("<script />", {
html: "appBuilder(team1, team2); // brand new, replaced code"
}));
}
appUpdate();
</script>
</body>
</html>

how to write <script> tag on javascript or jquery variable

this is the code i want to put in
var htm = "<center><div id="evp-8847b53dee625a133cfb02e88fd7bbf8-wrap" class="evp-video-wrap"></div><script type="text/javascript" src="http://convernet.evplayer.com/framework.php?div_id=evp-8847b53dee625a133cfb02e88fd7bbf8&id=Q29udmVybmV0L25ldyBjb252ZXJuZXQvVGhlIGZ1dHVyZS5tcDQ%3D&v=1333642408&profile=default"></script><script type="text/javascript"><!--
_evpInit('Q29udmVybmV0L25ldyBjb252ZXJuZXQvVGhlIGZ1dHVyZS5tcDQ=[evp-8847b53dee625a133cfb02e88fd7bbf8]');//--></script></center>"
$('#inner_slide .module').replaceWith(htm);
but its remove the script. please help
First of all, you need to escape the double-quote in the string; for example:
var myStr = "hi this is an \"inner quote\".";
Secondly, break up the string as such:
myStr += "some html: <scr"+"ipt>my script</s"+"cript>";
document.write(myStr);
That should work.
jQuery messes with script tags when you pass HTML to it.
You can use http://api.jquery.com/jQuery.getScript/ to pull in the script or use the native javascript option http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS
InnerHTML is also an option. You can check out this question Can scripts be inserted with innerHTML?

Categories

Resources