how to render a JS variable into a html element - javascript

I am new to Javascript and want to be able to display a JS variable onto my page without the user going into the console as it is neater, and I find a lot of people don't know about the console, and I don't want to use the alert() code. Can anyone help?

The code below accesses the paragraph with id "test" and print the value of "testVariable" into it.
var testVariable = "hello";
document.getElementById("test").innerHTML = testVariable;
<p id="test"></p>

I think this is what you need but this example is very simple i recommend you to google more and to keep open the JavaScript Doc for any questions.
The definition for innerHTML.
The Element property innerHTML gets or sets the HTML or XML markup
contained within the element.
// Your variable
let name = "Jhon"
// Get the HTML tag by ID and set the innerHTML
document.getElementById('name').innerHTML = name;
<div class="container">
<p>Hello <span id="name"></span></p>
</div>

Related

How do I define a variable in my index.html file? (window.parentPage = true;)

https://stackoverflow.com/a/43635720
On this answer, it says to define a variable (window.parentPage = true;) in the index.html page. How can I go about doing this?
You would need to define the variable using JavaScript. You can embed some JavaScript in the HTML file by encasing it in a script tag like so:
<script type="text/javascript">
window.parentPage = true;
</script>
First you need to clearly realize your reason... what you want to achieve.
After that defining that to yourself:
First option:
You can store/save some data as stated on the link you added to your question inside a tag, like that:
<script>
var myLittleBox = "box content";
</script>
And access it later like:
<script>
myLittleBox = myLittleBox + " extra content";
console.log(myLittleBox);
//this will print "box content extra content"
</script>
You need to use the tag to access the javascript environment.
Second option:
You can save/store data with pure HTML using an with type "hidden" to not show it on screen as an input box, and changing it's value, like that:
<input type="hidden" value="box content">
But this way you'll not be able to access the data directly without aid of javascript code, unless you send this input somewhere reachable as GET or POST within a and recover it getting the respective GET or POST.
Javascript variables:
https://www.w3schools.com/js/js_variables.asp
Ex: https://www.w3schools.com/js/tryit.asp?filename=tryjs_variables
HTML input:
https://www.w3schools.com/tags/tag_input.asp
HTML form handling:
https://www.w3schools.com/php/php_forms.asp
You're probably trying to understand the first option, but you question do not make that clear. Anyway, good studies.
Whatever you do you will have to use JavaScript in order to access the variable. An orthodox way of doing it that is not mentioned yet is using an data-attribute inside the html and than you access it by JavaScript:
const attributeName = 'data-parentPage';
const setup = () => {
let parentPageBool = document.querySelector(`html[${attributeName}]`).getAttribute(attributeName);
console.log(parentPageBool)
};
window.addEventListener('load', setup);
<html data-parentPage="true">
</html>

How to use .innerHTML in template element

I'm making an app with a framework that uses templates in HTML pretty heavily. It was all going well until I bumped into this problem:
Uncaught TypeError: Cannot read property 'querySelector' of null
correct me if I'm wrong, but I think this has to do with my code itself using templates and JavaScipt not being able to read the inside of that template.
Here's a minature version of my code which I am experiencing errors with.
HTML
<template id="main.html">
<p id="paragraph">This text needs to be changed in
JS</p>
<button onclick=example()>Click ME!</button>
</template>
JavaScript
function example (){
document.getElementById("paragraph").innerHTML = "This text has been changed!"}
Error:
Uncaught TypeError: Cannot read property 'innerHTML'
of null
Is there any way of avoiding this error?
1) Template-element content is not rendered by default
You can re-use the content in a template-element as many times as you want, but you need to manually specify that using Javascript. If you don't use any Javascript to render your template-element it won't be visible in the DOM. Resulting in your code not finding the paragraph (which is in the template-element).
2) Make sure you call your Javascript after the DOM is loaded
A web-page gets loaded from top to bottom. If you don't place your Javascript-code on the bottom of your body tag, or manually say it needs to be loaded after the DOM is ready, your code tries to find an element before that element even exists.
3) Your code has small mistakes like missing paragraphs etc.
Fix that using a good editor.
This example code shows you how it can be done:
Javascript:
function example() {
document.getElementById("paragraph").innerHTML = "This text has been changed!";
}
function init() {
//Get the template-element by id
let mainTemplate = document.getElementById("main");
//Create a new div-element to hold template content
let parent = document.createElement("div");
//IMPORTANT!
//Cloning template content into HTML DOM so it's visible.
//This part - content.cloneNode - makes your template content visible after being appended to the body, or another legal element in the DOM.
parent.append(mainTemplate.content.cloneNode(true));
//Append to body
document.body.append(parent);
}
//After dom is ready: Launch init function
document.onload = init();
HTML:
<template id="main">
<p id="paragraph">This text needs to be changed in
JS</p>
<button onclick="example()">Click ME!</button>
</template>
Working JSFiddle: https://jsfiddle.net/ovc1mrs2/
You probably want to append the content of your template directly to the body, or to another element.
I'm thinking you just forgot to put "()" after "function example."
function example() {
document.getElementById("paragraph").innerHTML = "This text has been changed!"}
<p id="paragraph">This text needs to be changed in
JS</p>
<button onclick=example()>Click ME!</button>
add "()" after example in js.
Updated Javascript code :
function example () {
document.getElementById("paragraph").innerHTML = "This text has been changed!"
};

Remove any specific html code using javascript

In the past I used Google Developer Console to delete some specific divs on a page. I could do it manually of course but in some cases where the divs where many I had to use the console. I had a single line code that did the job (I found it while searching the internet) but I lost my note.
So how can I delete using javascript any html code (by copy pasting the code).
Something like:
elements = $('<div ... </div>');
elements.remove();
OR
$('<div ... </div>').remove();
Any ideas? I am not an expert in javascript (obviously) and I've been searching stackoverflow for hours without finding anything that works.
UPDATE: I think some people might get confused with my question. Google developer console accepts javascript command lines. So even though I ask for javascript I will use the code on the google developer console.
UPDATE 2 :
Here is an example of a div I need to delete. Keep in mind I want to copy paste the entire code in the javascript code. Not just identify the div.
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
It's the data-entry-status="declined" that makes that div unique so I can't just identify the div using an id selector or a class selector. I need to put the entrire thing there and remove it.
I tried:
$('<div class="entry-status-overlay" data-entry-status="declined"><div class="entry-status-overlay__inner"><span class="entry-status-overlay__title">Declined</span></div></div>').remove();
It didn't remove the div.
Try to search the dom by its outerHTML.
function deleteDomByHtml(html){
html=html.replace(/\s/g,'');
$("*").each(function(){
if(this.outerHTML.replace(/\s/g,'')===html){
$(this).remove();
}
});
}
And try this line on this page:
deleteDomByHtml(`<span class="-img _glyph">Stack Overflow</span>`);
You cannot do by simply pasting the code. That will remove all the div element.
You may need a specific selector like id,class or child to specific parent to remove the element from the dom.
Consider this case the divs have common class but the data-entry-status is different. So you can get the dom using a selector and then check the dataset property.
For demo I have put it inside setTimeout to show the difference. In application you can avoid it
setTimeout(function() {
document.querySelectorAll('.entry-status-overlay').forEach(function(item) {
let getStatus = item.dataset.entryStatus;
if (getStatus === 'declined') {
item.remove()
}
})
}, 2000)
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div class="entry-status-overlay" data-entry-status="accepted">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">accepted</span>
</div>
</div>
Just add any attribute with [] and it will remove the element.
$('[class="entry-status-overlay"]').remove();
/*OR*/
$('[data-entry-status="declined"]').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
function del(){
var h = document.body.outerHTML;
h = h.match('<div>...</div>');
h.length--;
return h;
}
I guess this will work just give it a try... i tried on browser console and it worked, this way you can match the exact you want.
I might as well add my take on this. Try running this in your console and see the question vanish.
// convert the whole page into string
let thePage = document.body.innerHTML,
string = [].map.call( thePage, function(node){
return node.textContent || node.innerText || "";
}).join("");
// I get some string. in this scenario the Question or you can set one yourself
let replacableCode = document.getElementsByClassName('post-layout')[0].innerHTML,
string2 = [].map.call( replacableCode, function(node){
return node.textContent || node.innerText || "";
}).join("");
// replace whole page with the removed innerHTML string with blank
document.body.innerHTML = thePage.replace(replacableCode,'');
If you want to identify divs with that particular data attribute, you can use a data-attribute selector. In the example below, I've used a button and click event to make the demo more visual, but in the console the only line you'd need would be:
$('div[data-entry-status="declined"]').remove();
$(function() {
$("#testbutton").click(function() {
$('div[data-entry-status="declined"]').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="entry-status-overlay" data-entry-status="declined">
<div class="entry-status-overlay__inner">
<span class="entry-status-overlay__title">Declined</span>
</div>
</div>
<div id="x">Some other div</div>
<button type="button" id="testbutton">Click me to test removing the div</button>
See https://api.jquery.com/category/selectors/attribute-selectors/ for documentation of attribute selectors.
P.S. Your idea to paste some raw HTML into the jQuery constructor and then execute "remove" on it cannot work - you're telling jQuery to create an object based on a HTML string, which is, as far as it's concerned, a new set of HTML. It does not try to match that to something existing on the page, even if that exact HTML is in the DOM somewhere, it pays it no attention. It treats what you just gave it as being totally independent. So then when you run .remove() on that new HTML...that HTML was never added to the page, so it cannot be removed. Therefore .remove() has no effect in that situation.

copy html block with tags script

I have such html code:
<div>
<div id="text">text></div>
<script>$("#text").val('some value');</script>
</div>
I copy this html through .clone() and edit html inside. Result:
<div>
<div id="1-text">text></div>
<script>$("#text").val('some value');</script>
</div>
I want to change id inside tags script. $("#1-text").val('other value');
How can I do it?
You can simply add a variable to the outside that dynamically tells you what to select. so if you were to iterate through your values using a loop you can do something like this:
$("#text_"+i).val('other value');
You could also set a counter and as new divs are added the i increments. So it is flexible.
I'm not exactly sure what your end goal is but I wouldn't recommend this methodology if you're attempting to manipulate the javascript in the <script> tag. As I believe that would be cumbersome.
If you want to copy entire html block, you should bind your inline javascript code to this block as a container. Not id. So when you move or copy the block your script will be able to find any elements related to container.
<div id="containerOne" class="js-container">
<div class="js-text" data-text="some value">some value</div>
<script>
var $el = $("script").last().closest(".js-container").find(".js-text");
$el.text($el.data("text"));
</script>
</div>
Hereby you obtain access to elements by class not id. Note using "js-" prefix is just for javascript manipulation not for css styling.
Also you don't need to change script itself. You can change values via "data-" attributes.
In your external script you can encapsulate any clone logic by various methods. For example:
var myModule = {
clone: function(containerSelector) {
var $donorEl = $(containerSelector);
var $donorScript = $donorEl.find('script');
$script = $("<script />");
$script.text($donorScript.text());
$recipientEl = $donorEl.clone();
$recipientEl.attr('id', 'containerTwo');
var newValue = 'other value';
$('.js-text', $recipientEl).data('text', newValue);
$('body').append($recipientEl);
$('script', $recipientEl).replaceWith($script);
}
};
myModule.clone('#containerOne');
You can see the working example.

append value to element with javascript (not jquery)

<script>
var cool = "cool";
var pass = document.getElementById('name');
pass.innerHTML = cool;
</script>
<small id="name"></small>
To be honest I am just not searching correctly; this seems very basic. I have been using jquery for everything, but never actually used much JS by itself, so I am wondering how one would append a value to an element using just JS.
Your code should work, but you need to add it after the element is defined, otherwise document.getElementById('name') will return null as name element doesn't exist yet.
<small id="name"></small>
<script>
var cool = "cool";
var pass = document.getElementById('name');
pass.innerHTML = cool;
</script>
Your code should work... you have to define the JS after
<small id="name"></small>
If not there might be a problem which try to search DOM element before it loads
Basically you executing the javascript before creating the html
<small id="name"></small>
so the javascript does not work on the non-existent html .

Categories