Changing content in a div with JS without destroying its content - javascript

I am using an application where on change in the select box value my javascript function would be called. In the function I have an if/else statement. If the condition validates, it displays me a graph in my div, else it displays text in the same div.
var arrayDataSource = [];
//for example this array has the following [[1,0.2],[2,0],[3,1]
$.each(test, function(index, value)
{
//code to load data to that array
});
)
if(arrayDataSource.length > 0) {
//draw graph
} else {
document.getElementById('mydiv').innerHTML = "some text";
}
When I try to run the else condition my content gets overwritten as I am using an innerHTML to display text.
Do I have any other options to display text with javascript without using innerHTML? I have also seen some DOM functions and other relevant posts but nothing worked for me. My div properties should remain as they are even after the else condition.

Changing content in a div with JS without destroying its content you can simply use +=; instead of = only.
The code will be document.getElementById('overAllContainer').innerHTML += "some text";

Use insertAdjacentHTML instead of innerHTML as it does not reparse the element it is being used on and thus it does not corrupt the existing elements inside the element.
document.getElementById('overAllContainer').insertAdjacentHTML('beforeend', 'some text');
A better way to do it would be to append a new element with an attribute such as a class or an id to your overAllContainer in order to easily remove it when your selection changes.
You can do it via
document.getElementById('overAllContainer').insertAdjacentHTML('beforeend', '<p class="message">some text</p>');
Or via
var message = document.createElement('p');
message.setAttribute('class', 'message');
message.innerText = 'some text';
document.getElementById('overAllContainer').appendChild(message);
And then when you want to remove the message based on the selection changing,
document.querySelector('#overAllContainer .message').remove();

Use document.createTextNode:
var text = document.createTextNode("some text");
document.getElementById('mydiv').appendChild(text);

Related

Create html elements inside tooltip for a chrome extension

I want to create an HTML element (a div) using javascript to use that as a tooltip.
I can create the simple element by doing:
const element = document.createElement("div");
element.id = "myID"
and that works fine...however, I want to add a table (and some other HTML) inside the tooltip, so I was trying to do
element.appendChild(childElement); //where the childElement is another document.createElement("") that contains all the HTML I want.
or:
element.insertAdjacentHTML('afterbegin', '<table></table>');
however, nothing happens. there's no error, but it won't append it either. Am I missing something?
If it matters, this is happening inside the contentScripts.js of a chrome extension I'm building.
EDIT
Full code of div creation:
const element = document.createElement("div");
element.id = "tooltip-creation";
element.classList.add("tooltip");
const childElement = document.createElement("div");
childElement.id = "data";
//I've attempted to do .appendChild, innerHTML, and .insertAdjacentHTML (as can be seen here) and neither works but no error is given.
element.appendChild(childElement);
element.insertAdjacentHTML('afterbegin','<table border="1"><tr><td><strong>OMG</strong></td></tr></table>');
element.innerHTML = "<table border="1"><tr><td><strong>OMG</strong></td></tr></table>";
Separately I have 2 functions that do:
document.addEventListener("mouseover", function(e){
if (e.target.classList.contains("tooltip")) {
createTooltip(e);
}
});
document.addEventListener("mouseout", function(e){
if (e.target.classList.contains("tooltip")) {
removeAllTooltips();
}
});
I think your issue is that you're not actually appending the tooltip to anything. You need to append your element to a node that is already in the DOM. Here is a working example (without any CSS) that I got from your code, the only difference being that I appended the element node to an existing element in the DOM called root.
https://jsfiddle.net/irantwomiles/09o7vuj5/12/

get the html of element itself using jquery .html()

How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/

Adding but not Overwriting Text

I have a function called "StartMsg"
that I want to add text to a div element with the id "Screen". But sadly I known only basic JS, here is what I have so far;
function StartMsg() {
document.getElementById('Screen').innerHTML = "The game was created.";
}
But it overwrites all of my previous text (Yes I know it's supposed to do that, I'm trying to find a way to not overwrite but add!).
Use textContent and con-cat the new string
document.getElementById('Screen').textContent += " The game was created.";
JSFIDDLE
You can try createTextNode() method,
var your_div = document.getElementById('Screen');
var your_text = document.createTextNode("text added");
your_div.appendChild(your_content);
Using innerHTML will remove all listeners within the div element
You can also use the append method.
For example:
$('variable').append('some text');

Javascript not being called from hyperlink

I am using Google Apps Script to create a web app that contains several hyperlinks. When a hyperlink is clicked, it is supposed to trigger an alert box (just filler code to see if JS function is being called). My hyperlinks are being generated using this javascript function:
function updateAlertList(results) {
var div = document.getElementById('output');
div.innerHTML = '';
for (var i=0;i<results.length;i++)
{
div.innerHTML += '<p><a class="ra-button" href="javascript:void(0)" onclick="myJsFunc()">' + results[i].alertName + '</a></p>';
}
}
and the JS function that generates the alert is:
function myJsFunc(){
alert('this function was called');
}
For some reason, only the LAST hyperlink in the list of hyperlinks will trigger the JS function called myJsFunc. Whenever I click on any of the other hyperlinks that are earlier in the list, the JS function is not called. When I look in the console in Chrome Developer tools, I see the error "Cannot read property 'plugin_dispatchEvent___' of undefined"
Anybody know why the very last hyperlink in my list of hyperlinks works.. but the earlier ones don't?
I would change your code to this:
function updateAlertList(results) {
var div = document.getElementById('output');
div.innerHTML = '';
var alrtInnrHTML = '';
for (var i=0;i<results.length;i++) {
alrtInnrHTML += '<p><a class="ra-button" href="javascript:void(0)" onclick="myJsFunc()">' + results[i].alertName + '</a></p>';
console.log('alrtInnrHTML: ' + alrtInnrHTML);
}
}
div.innerHTML = alrtInnrHTML;
Please note that I created a variable alrtInnrHTML, and using += on the variable, not the innerHTML.
You are trying to use += on DOM manipulation instead of a variable. Set the HTML text string first, then inject the entire string just one time. Right now you are injecting HTML into the same DIV over and over and over again. Do all the links show up? In any case, even if your logic is working, I would change the logic to what I am suggesting, check that the final HTML content is correct with a console.log() output, and then inject the HTML all at once.
You would actually be better off adding individual <p> and <a> tags in each loop, and adding HTML in each loop rather than trying to construct a string of HTML.
You might want to do some reading about:
insertRow
insertCell
setAttribute
textContent
createTextNode
appendChild
createElement
With those methods you could avoid writing long HTML strings for the most part.
For example, you could create a table, with a new row for every result.
for (var i=0;i<results.length;i++) {
window.row1 = tblAlertList.insertRow(-1);
window.cell1 = row1.insertCell(0);
row1.setAttribute("class", "ra-button");
row1.innerHTML = <p><a class="ra-button" href="javascript:void(0)" onclick="myJsFunc()">' + results[i].alertName + '</a></p>';
}
That above code is just to give you an idea of what you might do, it's not working code.
Instead of creating a table, you could create an unordered list: <ul>
div.innerHTML = "<ul><a></a></ul>";
Then append a child to the last node in the list:
var node=document.createElement("LI");
var textnode=document.createTextNode("New Alert");
node.appendChild(textnode);
document.getElementById("myList").appendChild(node);

How to prevent script tags in text from executing?

I had a text box in my browser. Whatever you typed in the text box and clicked on okay button, the text submitted server through a AJAX request and then spread that message to remaining people, including to me also.
The message is appeared on a <div>.
What's my problem is if I typed html or script tags in that message they are not appearing in the message <div> and they are executing .
If I typed like tags opened and end with script in that middle code is executing on client side, how can I prevent executing and I am able to spread <script> tags also in the messages spreading to all.
If you want the text to always be text, treat is as text and don't use it to set innerHTML property for example.
Update text nodes instead.
Update
For example, if you had user input in userInput, and you wanted to display it, you would treat it as text, not HTML.
var element = document.body,
// For example
userInput = "Alex <script>alert('xss')</script>";
// Don't do this! Your input is text, not HTML.
// element.innerHTML = userInput;
// Use this instead
if ('textContent' in element) {
element.textContent = userInput;
} else {
element.innerText = userInput;
}
jsFiddle.
Have you tried replacing with html character entities? For example replacing all < with <.

Categories

Resources