Replace html placeholder text with html element using javascript - javascript

I have a scenario where i have in my page a placeholder text that I will replace after the page is fully loaded.
My problem is that the text i need to replace is a plugin of the recaptcha image, for example:
I have the text loading... which will be replaced by:
<recaptcha:recaptchacontrol ID='recaptcha' runat='server' PublicKey='kfldsjfh4378qyf43h4eidfhew' PrivateKey='sdflkdsfy908s6dfdsfkj' Theme='clean' />
I couldn't find a way to do so, any help will be appreciated.

found the answer in chat:
as the <recaptcha:...> tags are parsed by some server side plugin, they were not rendered after writing them in client side JS. so replacing works fine, but plugin didn't...

you can do any string operations (like search and replace) on document.body.innerHtml:
document.body.innerHtml = document.body.innerHtml.replace(/Loading\.\.\./g,
"<recaptcha...>");

Wrap your "Loading..." text in a <span> with a unique id, such as
<span id="removeme">Loading...</span>
Then, if you don't want to do much DOM-fu with that complex, namespaced tag, you can do the following:
var removeme = document.getElementById('removeme');
removeme.innerHTML = "<recaptcha:recaptchacontrol ...";
var recaptchaThing = removeme.firstChild;
removeme.removeChild(recaptchaThing);
var parent = removeme.parentNode;
parent.insertBefore(recaptchaThing, removeme);
parent.removeChild(removeme);
This will replace the <span> with the <recaptcha:recaptchacontrol> element, after letting the browser figure out how to build the DOM for that bizarre element. If it turns out <recaptcha:recaptchacontrol> can't be placed inside of a <span> element, make it a <div style="display:inline"> instead.

Related

Replace matching HTML tag with Regexp using JavaScript

[EDIT] First of all: I am aware that by DOM manipulation tools you can easily modify DOM structures. (These are available in every browser and even in Node by third party libraries.)
The goal of his question is if someone can come up with a clever idea if this problem can be solved by Regexp in JavaScript without DOM.
Thank you![End of EDIT]
Let's say I have the following HTML snippet as a string:
<p>
<div class="something">
<span>
<div class="else">My precious text.</div>
</span>
</div>
</p>
I wish to get rid of the <div class="something"> tags with RegExp in order to get something like this (indentation does not matter):
<p>
<span>
<div class="else">My precious text.</div>
</span>
</p>
So, my attempt was:
htmlString.replace(/<div class="something">([\s\S]+?)<\/div>/gi, "$1");
But it will match for the closing tag of <div class="else"> of course.
How can I do it properly using just vanilla JS and by not using the DOM manipulation tools of the browser? (i.e. in Node)
Regex isn't the best option for this. You're better off using the querying abilities of JS if it's HTML you're dealing with, here's a quick example of what you could do (oversimplified for explanation purposes):
var htmlString = '<p><div class="something"><span><div class="else">My precious text.</div></span></div></p>';
//Create a DOM element so you can query what you need and manipulate it
var newElement = document.createElement("p");
newElement.innerHTML = htmlString;
//Find what you need to remove
var toRemove = newElement.getElementsByClassName("something")[0];
//Grab what you need to keep
var toKeep = toRemove.firstChild;
//Remove the unwanted element
newElement.removeChild(toRemove);
//Append the old child
newElement.appendChild(toKeep);
//If you really want it back as a string
newElement.outerHTML;
PS: It's not valid to have a div inside a paragraph element, so you're going to get unpredictable results.

replace content of div with another content

I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)

add an <a> element to Google Document using Apps Script

I want to include a "properly formatted" mailto: link in a paragraph of text in my document:
"Please contact me if you have any questions."
The only way I can think of doing this is with multiple Paragraphs and Styles, which I don't think would be an elegant solution. I was wondering if there was just some easier way of including an <a> tag directly in the document. The Text object has a setLinkUrl() method, but I'm not sure how to create a Text object! var link = "my link text" creates a String.
A working solution using the paragraph class,
var par1a = doc.appendParagraph("Please ");
var link = doc.appendParagraph("Contact me ").setLinkUrl("mailto:me#me.com");
link.merge();
var par1b = doc.appendParagraph("if you have any questions.");
par1b.merge();

string search in body.html() not working

Hi here is my total work to search a string in HTML and highlight it if it is found in document:
The problem is here
var SearchItems = text.split(/\r\n|\r|\n/);
var replaced = body.html();
for(var i=0;i<SearchItems.length;i++)
{
var tempRep= '<span class="highlight" style="background-color: yellow">';
tempRep = tempRep + SearchItems[i];
tempRep = tempRep + '</span>';
replaced = replaced.replace(SearchItems[i],tempRep); // It is trying to match along with html tags...
// As the <b> tags will not be there in search text, it is not matching...
}
$("body").html(replaced);
The HTML I'm using is as follows;
<div>
The clipboardData object is reserved for editing actions performed through the Edit menu, shortcut menus, and shortcut keys. It transfers information using the system clipboard, and retains it until data from the next editing operation replace s it. This form of data transfer is particularly suited to multiple pastes of the same data.
<br><br>
This object is available in script as of <b>Microsoft Internet Explorer 5.</b>
</div>
<div class='b'></div>
If I search for a page which is pure or without any html tags it will match. However, if I have any tags in HTML this will not work.. Because I am taking body html() text as the target text. It is exactly trying to match along with html tags..
In fiddle second paragraph will not match.
First of all, to ignore the HTML tags of the element to look within, use the .text() method.
Secondly, in your fiddle, it wasn't working because you weren't calling the SearchQueue function on load.
Try this amended fiddle

Find + replace content of an element without losing events

I have a function that reads the content of an element, replaces a word with a link and then rewrites the content back into the element. Obviously this means that all events that were previously set are lost.
Does anyone know of a function/method that could find and replace the content of an element without losing the events?
Edit: Without using a library
Here is my current code that does not destroy the events but turns <, for example, into <, so I can not append HTML. This is the closest I have got:
element.appendChild(document.createTextNode(content));
My original code worked but got rid of the events:
element.innerHTML += content;
By using jQuery you could do it with the text() method
var str = $('#element-id').text();
str = yourReplaceFunction(str);
$('#element-id').text(str);
Edit:
Another option would the innerHTML property. It's not very elegant but works nevertheless.
var strElem = document.getElementById('element-id');
var str = strElem.innerHTML;
str = yourReplaceFunction(str);
strElem.innerHTML = str;
Edit2:
Yet another option would be to wrap the text you want to replace inside of a separate tag, for example <span>.
<div id="container">
<a id="link-with-events">Link</a>
<span id="replaceable">The Text Gets Replaced</span>
<a id="more-links-with-events">Another Link</a>
</div>
Then you'd simply access and replace the contents of the span tag, leaving the surrounding elements untouched.
Assuming the tag contains just text (and not additional tags):
element.firstChild.nodeValue=content;
See https://jsfiddle.net/Abeeee/ubj6hte4/

Categories