the reason why Conflict between plugin and javascript function occured - javascript

Few days ago I had to write code quickly and added the bad code below.
<td class="note_box_con" onclick="getElementsByTagName('a')[0].click();">
After then, when I tried to use Text editor plugin written by Javascript, I found
Text editor plugin and the function of DOM collide into each other
Now I know what was the problem and solve it. But I cannot understand what kind of risk getElementsByTagName('a')[0].click(); has.
In my incomplete view, that code is just addEventlistener function().....
what kind of risk onclick="getElementsByTagName('a')[0].click();" has?

In my understanding, its a bad practice to do it this way. I would rather suggest you to use to fetch using classname or id.
If you are using some resource that adds anchor tags to your page, this will break your logic.
Following is a simulation:
var count = 0;
function addAnchor(){
var div = document.getElementById("content");
var str = "<a href='#'>" + count++ + "</a>";
div.innerHTML = str + div.innerHTML;
}
document.getElementsByTagName("a")[0].addEventListener("click", function(){
console.log(this.innerHTML);
return false;
})
<div id="content">
Test
</div>
<button onclick="addAnchor()">Add Link</button>
<a onclick="document.getElementsByTagName('a')[0].click()"> test </a>
Also, if there is a change in DOM structure, your code will not work properly. Best use a proper selector that uniquely identifies the element.

Related

How to document.write to parent element when external javascript called

Hello my question is how to write inside script called parent element with document.write when parent element is unknown
You may consider this as advertising script
For example:
<div>
<script src="http://www.pokemonpets.com/scripts/ads_simple.js"></script>
</div>
My script code below but not working right now
document.write('<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>');
So somehow i have to make it work without knowing parent element or without knowing whether page has JQuery or not.
How does advertising companies handle this?
You don't want to use document.write, you want to find your script tag and replace it with your new content. You can do that by looking for a script tag with your URL, then having it's parent replace it.
scripts = document.getElementsByTagName("script");
for(var i in scripts){
if(scripts[i].src.indexOf('//www.pokemonpets.com/scripts/ads_simple.js') !== -1){
var wrapper = document.createElement('div');
wrapper.innerHTML = '<a title="Bedava Pokemon Online Oyunu" target="_blank" href="http://www.pokemonpets.com/Register"><img src="http://orig04.deviantart.net/58d0/f/2015/213/8/4/pokemonpets_by_monstermmorpg-d93plr1.png" /></a>';
scripts[i].parentElement.replaceChild(wrapper,scripts[i]);
}
}
This is totally untested, not even for syntax, so you might need to fiddle with it a bit.

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 do I dynamically append a large block of HTML to a div?

I'm trying to learn web development, so I don't have much experience with the various languages and markups yet. I'm making a website with a blog that reads JSON data from the Tumblr v2 API. After getting the JSON data from Tumblr I want to add some of the data from each post to my own website's blog, here's the code that I've been trying to use..
<script>
function loadBlogPosts(){
$.getJSON("http://api.tumblr.com/v2/blog/[MY_BLOG]/info?api_key=[MY_KEY]",
function(blogData){
$.each(blogData.posts, function(){
$(#main_content).append( [BUNCH OF NESTED HTML] );
});
}
);
}
</script>
Before writing this, I thought it would be a good idea to make a 'layout' of each blog post in divs. So i came up with this:
<div class="post">
<div class="post_header">
<div class="post_title"></div>
<div class="post_author"></div>
<div class="post_date"></div>
</div>
<div class="post_content"></div>
<div class="post_footer"></div>
</div>
But that's where I'm stuck. I know what I want to do, but I don't have enough experience with JavaScript/JQuery/JSON/HTML to know how to do it. I want parse the JSON blog data and, for each post, take the post content and apply it to that div structure while writing/appending it to the "main_content" div.. I tried copy-pasting that group of divs into the append function surrounded by quotes, but it became a real mess of quotes and slashes, and it didn't look like it was working correctly..
So, whats the best way for me to do that? Is there a good way of applying a big chunk of nested HTML elements while populating them with content from my JSON data? If not, what should I do? I'm still very new to HTML, JavaScript, and web coding in general, so I may be going about this completely wrong!
If you want HIGH PERFORMANCE:
In pure javascript the highest performing method is probably using createDocumentFragment()
function postEl(json){ // create a function for the POST element
var post=document.createElement('div');
post.className='post';
var postHeader=document.createElement('div');
postHeader.className='post_header';
var postTitle=document.createElement('div');
postTitle.className='post_title';
postTitle.tectContent=json.title;
//more code
postHeader.appendChild(postTitle);
//more code
post.appendChild(postHeader);
return post;
}
function appendPosts(){ // append each post to a fragment. and then to the main
var frag=document.createDocumentFragment();
for(/*each post*/){
frag.appendChild(postEl(/*jsonPost*/));
}
document.getElementById('main_content').appendChild(frag);
}
Precreating the structure should also increase the performance.
cloneNode
https://developer.mozilla.org/en-US/docs/Web/API/Node.cloneNode
https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment
cloning the node also increases the performance by setting the valuse directly without recreating each individual node.
function appendPosts(js){
var node=document.createElemtnt('div'),
frag=document.createDocumentFragment();
node.innerHTML='<div class="post_header"><div class="post_title"></div><div class="post_author"></div><div class="post_date"></div></div><div class="post_content"></div><div class="post_footer"></div>';
for(var a=0,b;b=js.posts[a];++a){
var newNode=node.cloneNode(true),
childs=newNode.childNodes,
header=childs[0].childNodes;
header[0].textContent=b.title/*title from Postdata*/;
header[1].textContent=b.author/*author from Postdata*/;
header[2].textContent=b.date/*date from Postdata*/;
childs[1].textContent=b.content/*content from Postdata*/;
childs[2].textContent=b.footer/*footer from Postdata*/;
frag.appendChild(newNode);
}
document.getElementById('main_content').appendChild(frag);
}
function loadBlogPosts(){
$.getJSON("http://api.tumblr.com/v2/blog/[MY_BLOG]/info?api_key=[MY_KEY]",
appendPosts
)
This function should work now .. but as i don't exactly know the json response you may need to change the various post keys.
note: i put the fragment thing in a function so you have an idea how it works.
you should put the postEl content inside the appendPosts function... (thats also faster)
if you have any questions just ask.
EDIT
no they are not globals
var a,b,c,d; // not globals == var a;var b;var c;var d;
var a,b;c;d; // c d = gobal
// , comma affter a var allows you to not write 1000 times var.
EDIT2
//.......
frag.appendChild(newNode);
}
var topNode=document.createElement('div');
topNode.className='post';
topNode.appendChild(frag);
document.getElementById('main_content').appendChild(topNode);
//.....
when you want to do everything with jquery yoiu could use something like this:
var post = $('<div class="post"></div>');
var postheader = $('<div class="post_header"></div>');
postheader.append('<div class="post_title"></div>');
postheader.append('<div class="post_author"></div>');
post.append(postheader);
post.append('<div class="post_content"></div>');
post.find('.post_title').text('my title');
post.find('.post_content').text('my content');
$('#main_content').append(post);
instead of .text('my title') you can use .text(variable) of course
Write your code in a separate page, then append a whole html page into a div by using:
$('#containerDiv').load('page.htm');
Also, this is a good way to fragment the content.
you could do something like this:
$.each(blogData.posts, function(i,v){
var cnt= '<div class="post">' +
'<div class="post_header">' +
'<div class="post_title">'+ blogData.posts[i].title +'</div>' +
'<div class="post_author">'+ blogData.posts[i].author +'</div>' +
'<div class="post_date">'+ blogData.posts[i].date +'</div>' +
'</div>' +
'<div class="post_content">' +
blogData.posts[i].body +
'</div>' +
'<div class="post_footer">' +
'</div>' +
'</div>';
$('#main_content').append(cnt);
});
Note that you don't need to split up all the lines, i've just done that to make it more readable. (I'm also not sure if all the variables are correct, (i don't think author exists) but it's just as a demo)

.html() and .append() without jQuery

Can anyone tell me how can I use these two functions without using jQuery?
I am using a pre coded application that I cannot use jQuery in, and I need to take HTML from one div, and move it to another using JS.
You can replace
var content = $("#id").html();
with
var content = document.getElementById("id").innerHTML;
and
$("#id").append(element);
with
document.getElementById("id").appendChild(element);
.html(new_html) can be replaced by .innerHTML=new_html
.html() can be replaced by .innerHTML
.append() method has 3 modes:
Appending a jQuery element, which is irrelevant here.
Appending/Moving a dom element.
.append(elem) can be replaced by .appendChild(elem)
Appending an HTML code.
.append(new_html) can be replaced by .innerHTML+=new_html
Examples
var new_html = '<span class="caps">Moshi</span>';
var new_elem = document.createElement('div');
// .html(new_html)
new_elem.innerHTML = new_html;
// .append(html)
new_elem.innerHTML += ' ' + new_html;
// .append(element)
document.querySelector('body').appendChild(new_elem);
Notes
You cannot append <script> tags using innerHTML. You'll have to use appendChild.
If your page is strict xhtml, appending a non strict xhtml will trigger a script error that will break the code. In that case you would want to wrap it with try.
jQuery offers several other, less straightforward shortcuts such as prependTo/appendTo after/before and more.
To copy HTML from one div to another, just use the DOM.
function copyHtml(source, destination) {
var clone = source.ownerDocument === destination.ownerDocument
? source.cloneNode(true)
: destination.ownerDocument.importNode(source, true);
while (clone.firstChild) {
destination.appendChild(clone.firstChild);
}
}
For most apps, inSameDocument is always going to be true, so you can probably elide all the parts that function when it is false. If your app has multiple frames in the same domain interacting via JavaScript, you might want to keep it in.
If you want to replace HTML, you can do it by emptying the target and then copying into it:
function replaceHtml(source, destination) {
while (destination.firstChild) {
destination.removeChild(destination.firstChild);
}
copyHtml(source, destination);
}
Few years late to the party but anyway, here's a solution:
document.getElementById('your-element').innerHTML += "your appended text";
This works just fine for appending html to a dom element.
.html() and .append() are jQuery functions, so without using jQuery you'll probably want to look at document.getElementById("yourDiv").innerHTML
Javascript InnerHTML
Code:
<div id="from">sample text</div>
<div id="to"></div>
<script type="text/javascript">
var fromContent = document.getElementById("from").innerHTML;
document.getElementById("to").innerHTML = fromContent;
</script>

How to remove HTML tags from textarea with JavaScript

I'm loading text from database but I'd like to remove html link code from it with JavaScript.
So lets say the textarea right now displays:
<a rel="nofollow" href="http://stackoverflow.com//questions/ask">http://stackoverflow.com//questions/ask</a> - good page
and I want it to display:
http://stackoverflow.com//questions/ask - good page
Is there something lightweight I could use that would work for multiple links in the same textarea?
Inspired by this answer, use the browser's HTML parsing abilities to get this done right.
function strip(html)
{
var tmp = document.createElement("DIV");
tmp.innerHTML = html;
return tmp.textContent||tmp.innerText;
}
jQuery('#textareaid').text(function(index, text){
return strip(text);
});
Here's the JSFiddle of it working: http://jsfiddle.net/Au95R/1/
(Edited to use cleaner JS)
You could use strip_tag() like in PHP: http://phpjs.org/functions/strip_tags:535
textareacontent = strip_tags(textareacontent, "<b><i>"); // remove all HTML except <b> and <i>.
you can do this using regular expressions. here is a question on stack overflow itself and the answer explains it well

Categories

Resources