Remove Html Element before it is rendered in page using javaScript? - javascript

I am working in very large project without Using any js Framework and Lib . I had a serious problem where I am looking for way to remove the HTML element before it is rendered in page. The code shown below is not actual problem but it helps me to find my actual solution . Please help me ?
code:-
var element = document.createElement('div');
element.innerHTML = 'This is Nirikshan Bhusal'
element.remove()
document.getElementById('root').appendChild(element);
I want logic something that above code shows.
I have 1 solution for this problem but this doesn't work for me
Codes That doesn't solve my problem :-
var element = document.createElement('div');
element.innerHTML = 'This is Nirikshan Bhusal';
element.style.display = 'none';
document.getElementById('root').appendChild(element);
element.remove();
Please help me ?

You cannot do that with native elements. But you could easily monkey patch it:
Element.prototype.remove = (old => function() {
this.dontAdd = true;
old.call(this);
})(Element.prototype.remove);
Element.prototype.appendChild = (old => function(el) {
if(!el.dontAdd) old.call(this, el);
})(Element.prototype.appendChild);
So now your first version works as expected. But this can cause side effects all over your code, so be careful with this.

Related

JavaScript - Uncaught TypeError: Cannot read properties of undefined (reading 'style') [duplicate]

I would like to change the color, fontsize and font weight of the text in a span element of the html page.
I am using the following code:
if(window.location.href.indexOf("test") > -1){
var search_span = document.getElementsByClassName("securitySearchQuery");
search_span[0].style.color = "blue";
search_span[0].style.fontWeight = "bold";
search_span[0].style.fontSize = "40px";
}
Following is the code for my html page
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
I thought of getting elements by id but unfortunately they only classes and no ids. I do not have access to change the html code but just to add js code to website externally.
I have tried to look into other stackoverflow posts but could find the solution.
Am new to js and css,Please let me know where am going wrong.
Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.
If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.
You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.
This works when you execute it in Dev Tools because the DOM is already loaded.
It's currently working, I've just changed the operator > in order to work in the snippet, take a look:
window.onload = function() {
if (window.location.href.indexOf("test") <= -1) {
var search_span = document.getElementsByClassName("securitySearchQuery");
search_span[0].style.color = "blue";
search_span[0].style.fontWeight = "bold";
search_span[0].style.fontSize = "40px";
}
}
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>

My code executed only in console but not working in .js file

I have tried the following code to replace text character to the img tag inside div message.
However the code is working fine while i do in console. But when I try the same in my sticker.js is not working. Can anyone tell me the reason?
The idea to make sticker box for chat app codded with Javascript and jQuery.
User 1 will send :sticker1: to public room and replaced with img src inside the #div
Now I'm trying document to call the script when div is showing but still not working.
$(document).ready(function() is not working
And $(function() is not working either.
My chat app using template folder /template/*.php and web-cache folder to load the design. I am searching every where to find some solution but no luck.
I need help please
$("#chat-sticker-container").ready(function stickers() {
var emoCodes = [
':sticker1:',
];
var $this = $("body");
emoCodes.forEach(function(code) {
var image = '<img src="https://sevendays.co.in/wp-content/uploads/2019/02/' + code.replace(/:/g, "") + '.jpg">';
$this.find('p.chat-sticker').html(function(index, html) {
return html.replace(new RegExp(code, "g"), image);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/sticker.js"></script>
<dive id="chat-sticker-container">
<p id="chat-sticker" class="chat-sticker">:sticker1:</p>
</dive>
Make sure your JS is executing AFTER the html is in the DOM, this includes putting your script at the end of your body tag.
Since the script is called before the html is defined its essentially working with nothing, putting the after the html should fix the issues.
By looking at your JSFiddle example I think you need to use the MutationObserver API. This way you can check if an element, or the children of an element have been changed, added or removed.
I'm not able to figure out what the container is where the chat divs are added to the page, so I can only instruct you. But based on your fiddle I'm selecting the chat-main-scroll-chatroom div.
// List of emoCodes
var emoCodes = [
':sticker1:',
];
// Select chat container. Change if necessary.
var chatContainer = document.getElementById('chat-main-scroll-chatroom');
// Create a new observer.
var observer = new MutationObserver(function(entries) {
// Check for emocodes whenever something has changed.
emoCodes.forEach(function(code) {
var image = '<img src="https://sevendays.co.in/wp-content/uploads/2019/02/' + code.replace(/:/g, "") + '.jpg">';
$('p.chat-sticker').html(function(index, html) {
return html.replace(new RegExp(code, "g"), image);
});
});
});
// Check if children are changed
var options = { childList: true }
// Observer the chat container and check if itself or children are changing.
observer.observe(chatContainer, options);
So I really hope that this will help you out. In the best case scenario you would be able to filter the text that has been sent before the message is sent. If the API of your chat app provides such controls, then please use them.
Best of luck!

Place cursor at the end of text in an iframe body element with JavaScript

I'll start by apologising as this may seem like or actually be a duplicate, but I've tried every solution I've encountered and none seem to be working for me.
In my HTML I have an iframe referencing another HTML document. With JavaScript, at the press of a list of buttons I insert text into the body of that iframe. I also use JavaScript to maintain focus on the iframe body. The problem is that nothing appears to work for me to get the cursor to move to the end of the text each time I press those buttons, it always moves to the beginning.
One of the solutions I've tried was to add this code to the function that handles my button presses:
iFrameBody.focus();
var content = iFrameBody.innerHTML;
iFrameBody.innerHTML = content;
so the function looks like this:
function typeIn(buttonId) {
var iFrameBody = document.getElementById("iFrame").contentWindow.document.body;
iFrameBody.innerHTML += buttonId;
iFrameBody.focus();
var content = iFrameBody.innerHTML;
iFrameBody.innerHTML = content;
}
Something else I tried was, in the HTML file referenced by my iframe I did:
<body onfocus="this.innerHTML = this.innerHTML;"></body>
I tried several other more complicated solutions that frankly I didn't even quite understand to be honest, all to no avail. Any help would be much appreciated.
I figured it out. The issue was that I was using a body element, writing to it's innerHTML and trying to set focus on the body. By simply using a textarea inside my iFrame instead it became very simple and it only required the simplest code.
This to set focus when the page loads:
window.onload = function () {
var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameTextArea");
iFrameTextArea.focus();
}
And then this to set the button to write to the textarea while maintaining focus:
function typeIn(buttonId) {
var iFrameTextArea = document.getElementById("iFrame").contentWindow.document.getElementById("iFrameInput");
iFrameTextArea.focus();
iFrameTextArea.value += buttonId;
}
Super easy!!
Instead of again using textarea in iframe, u can also solve this by using the following code.
var iframeElement = document.getElementById("iFrame").contentWindow.document.body;
iframeElement.focus();
var len = iframeElement.length ;
iframeElement.setSelectionRange(len, len);

Iframe nomenucontext - Modify img tag after creation

Hi I am adding a iframe dynamically, It displays an image from a server. I need to disable the context menu for this item. In chrome I can inspect element and if I add oncontextmenu="return false" I do get the wanted affect. However I am unable to do this while the page is generated. Here is an example of the working html.
However I can not reproduce this when i frame is being created. Here is my code.
$(window).scrollTop(0);
$('#secVerify').show();
$("#popWaitLoad").modal("hide");
imgLoading.hide();
dvIframe.empty();
//else load deposit data into interface
$("#spanType").text(deposit.DepositType);
$("#spanReference").text(deposit.Reference);
$("#spanAmount").text("R " + deposit.Amount.toFixed(2));
$("#spanDate").text(deposit.DateCreatedOffsetS);
imageID = deposit.Deposit_Doc_imageID;
var url = imageUrl + '/' + deposit.Deposit_Doc_imageID + '/false';
var imgFrame = document.createElement("iframe");
imgFrame.src = url;
imgFrame.frameBorder = '0';
imgFrame.scrolling = 'no';
imgFrame.width = '100%';
imgFrame.height = '100%';
imgFrame.align = 'middle';
imgFrame.id = "iframeImg";
dvIframe.append(imgFrame);
I have tried examples like.
$("#iframeImage").contents().find("img").attr("oncontextmenu", 'return false');
$('#iframeImage img').on('contextmenu', function (e) {
e.stopPropagation();
// Your code.
return false;
});
But because the img element seems to be only created is done after page load it seems to not work. I know disabling the the menu will not help much and I have explained all the other methods of obtaining the image that is still available but the client really wants this.
I have added nocontextmenu to the body tag and it works everywhere except for the iframe.
So let me clarify, My iframe is working like it should however I would like to disable the right click aka context menu on the specific iframe.
I have used setAttribute to set the attributes and targeted a container to appendChild.
function example(){
var target = document.getElementById('container');
var element = document.createElement('img');
element.setAttribute('src', 'http://gopalshenoy.files.wordpress.com/2011/04/product_demos.jpg');
//element.setAttribute('width','100%');
//element.setAttribute('height','100%');
element.setAttribute('id','iframeImage');
element.setAttribute("oncontextmenu","return false;");
target.appendChild(element);
}
// Demo-Snippet use.
window.onload=example;
<!-- Demo Snippet use -->
<div id="container"></div>
If you build more than one element using this function you might find further issues due to duplicated ID's.
ID's are used to target a specific element 'one of' so if you want to build multiple elements I would recommend giving them unique ID's.
I hope this helps. Happy coding!

jquery replaceWith not working on google chrome

I am facing a strange problem with dynamically replacing controls using javascript in Google Chrome. The replaced controls dont show up in UI but when i use developer tools i am able to locate the replaced element but it does not show up until i close the developer tools. once i open and close developer tools the issue is no longer replicatable until i refresh the page.
This happens only in cases where i am trying to replace outerHTML of an element.
I first tried using jquery's replaceWith api, that dint help so i switched to the following script -
function chromeOuterHTML(oldElem, outerhtml)
{
var el = document.createElement('div');
el.innerHTML = outerhtml;
var parentNode = oldElem.parentNode;
var range = document.createRange();
range.selectNodeContents(el);
var documentFragment = range.extractContents();
parentNode.insertBefore(documentFragment, oldElem);
parentNode.removeChild(oldElem);
}
I dont think that its a problem with my javascript since the problem is specific to chrome and also happens in only certain cases.
Any help would be greatly appreciated
More a diagnostic tool than a solution, but have you tried delaying your insertBefore?
function chromeOuterHTML(oldElem, outerhtml)
{
var el = document.createElement('div');
el.innerHTML = outerhtml;
var parentNode = oldElem.parentNode;
var range = document.createRange();
range.selectNodeContents(el);
var documentFragment = range.extractContents();
setTimeout(function () {
parentNode.insertBefore(documentFragment, oldElem);
parentNode.removeChild(oldElem);
}, 1);
}
In some situations (that I don't fully understand), DOM manipulations can fail if they happen in too quick a succession. This modification will delay (only by 1ms) the insert - it's possible that it will make a difference. It's also possible it'll do nothing!

Categories

Resources