getElementByClassName multiple use and display in <title> - javascript

I'm using the getElementByClassName function to change the displayed text.
I'm running into 2 different problems.
Problem 1:
I want to change my <title></title> to the value of var value.
It doesnt work the like the displayed text in the body element.
Problem 2:
Now I'm using 4 different variables because I can only declare a getElementsbyClassName once every class. I there a way to write this code more beautiful/compacter?
Any help would be appricated,
<!DOCTYPE html>
<html lang="">
<head>
<title><!--VALUE HERE<div class="div0"></div>--></title>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<script>
var value= "Banana";
//var vartest0 = document.getElementsByClassName("div0");
var vartest1 = document.getElementsByClassName("div1");
var vartest2 = document.getElementsByClassName("div2");
var vartest3 = document.getElementsByClassName("div3");
//vartest0[0].innerHTML = value;
vartest1[0].innerHTML = value;
vartest2[0].innerHTML = value;
vartest3[0].innerHTML = value;
</script>
</body>
</html>

To set the value for title, you need to do document.title = "Banana"; or document.title = value;.
<!DOCTYPE html>
<html lang="">
<head>
<title></title>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
<script>
var value= "Banana";
document.title = value;
var vartest1 = document.getElementsByClassName("div1");
var vartest2 = document.getElementsByClassName("div2");
var vartest3 = document.getElementsByClassName("div3");
//vartest0[0].innerHTML = value;
vartest1[0].innerHTML = value;
vartest2[0].innerHTML = value;
vartest3[0].innerHTML = value;
</script>
</body>
</html>

I’d suggest:
// use document.querySelectorAll() to retrieve all the elements
document.querySelectorAll(".div1,.div2,.div3")
// use NodeList.forEach() to iterate over all the
// returned Nodes
.forEach(
// using an Arrow function ("el" is a reference to the
// current Node of the NodeList), here we update the
// textContent of each Node to the "value" variable:
(el) => el.textContent = value);
// and set the document.title to that same variable:
document.title = value;

Related

JavaScript querySelector not working when .value is added to it

I am creating my program which takes the user input on an Enter key.
I use the userInput with .value in the if statement and it works perfectly. But when I try to use it as a variable, nothing is outputted and nothing is in the console.
I tried to do querySelector("input['name = "command"]') to see if it might work but again, nothing outputted and it showed nothing in the console
var userInput = document.querySelector("input[name = 'command']")
var theInput = userInput.value.toLowerCase();
var theConsole = document.querySelector("#console");
theConsole.scrollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) {
acceptCommand();
setInterval(scrollUpdate, 1000)
}
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(theInput=== "help") theConsole.append("Help is given!", p);
//using the keywords
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input type = "text" name = "command" id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
</body>
</html>
Replace the div#console element:
<div id="console">
to this input:
<input type="text" id="console">
You will want to refer to userInput.value instead of theInput. Because theInput is set to the value at the time of setting the variable and it doesn't get updated even though the value of userInput changing.

How to reduce javascript code that use JQuery and .each()

I have tried to reduce following code
var wgDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.each
(function(nIndex)
{
var sWidgetName = $(this).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
});
to this code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.children(":first-child");
var sWidgetName = jqDialog.attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
but this doesn't work !
The sWidgetName variable is always undefined in last code.
What is my mistake ?
With help of comments, I have found a solution.
I must use get(0) to obtain first element in list returner by JQuery().
And I must use $(jqDialog) instead of jqDialog to get 'data-widgetvar' attribute.
Here is my new code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.get(0);
var sWidgetName = $(jqDialog).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
Assuming you want to access an element with attribute data-widgetvar nested in an element having css classes ui-dialog and ui-overlay-visible you could do the following with plain javascript:
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
querySelector allows a CSS like selector combining class together with attribute selector.
Update:
Here is a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test</title>
<script type="text/javascript">
function main() {
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
console.log("Attribute value", myElement.getAttribute('data-widgetvar'));
}
document.addEventListener("DOMContentLoaded", main);
</script>
</head>
<body>
<div class="ui-dialog ui-overlay-visible">
<div>some element</div>
<div data-widgetvar="someValue">some text content</div>
</div>
</body>
</html>

Convert a HTML Collection to Javascript Array?

I am a newbie, trying to learn w3c-dom, html-dom, just went through this DOM-Introduction
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>
While logging this on console, i got just an empty array, when i tried to convert the HTMLCollection to Array.
Note: Tried using for-loop also.
Attached the console output,
Yes, adding
document.addEventListener('DOMContentLoaded', function() { //rest of the code });
fixes the issue
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM</title>
</head>
<body>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
var getByTag = function(selector) {
// FIXME: Do more conditions -- Come Up with more non-verbose regex condition
return /\w/i.test(selector) ? document.getElementsByTagName(selector) : null;
}
var isHTMLCollection = function(data) {
return data.toString() === '[object HTMLCollection]';
}
var toArray = function(c) {
return Array.prototype.slice.call(c);
}
var getAllPs = getByTag('p');
console.log(isHTMLCollection(getAllPs), 'isHTMLCollection');
console.log(Array.isArray(getAllPs), 'isArray-1');
console.log(getAllPs, 'getAllPs');
var _arrayLike = toArray(getAllPs);
console.log(Array.isArray(_arrayLike), 'isArray-2');
console.log(_arrayLike.length, 'Array.length');
});
</script>
<p id="p1">
First Para
</p>
<p id="p2">
Second Para
</p>
</body>
</html>
Note: Problem with chrome console is, array values are evaluated on asynchronously.
Thanks to #somethinghere & #trincot.

Cannot set property 'innerHTML' of null while still using window.onload to delay

I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>

Bold text in body using javascript

This code is attempting to highlight (by adding 'bold' tag) some characters that are in the HTML body. (These are specified in the JS function)
But instead of the text becoming bold, I get the 'bold' tag as the result in the html page that is getting rendered.
While I want some thing like
This is a test message
I get
This is a test <b>message</>
Any help would be awesome.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var children = document.body.childNodes;
for(var len = children.length, child=0; child<len; child++){
if (children[child].nodeType === 3){ // textnode
var highLight = new Array('abcd', 'edge', 'rss feeds');
var contents = children[child].nodeValue;
var output = contents;
for(var i =0;i<highLight.length;i++){
output = delimiter(output, highLight[i]);
}
children[child].nodeValue= output;
}
}
}
function delimiter(input, value) {
return unescape(input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3'));
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
The problem is that you are putting HTML in to a text node, so it is being evaluated strictly as text. One easy fix would be to simply operate on the innerHTML of the body element, like this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Test</title>
<script>
function myFunction(){
var highLight = ['abcd', 'edge', 'rss feeds'],
contents = document.body.innerHTML;
for( i = 0; i < highLight.length; i++ ){
contents = delimiter(contents, highLight[i]);
}
document.body.innerHTML = contents;
}
function delimiter(input, value) {
return input.replace(new RegExp('(\\b)(' + value + ')(\\b)','ig'), '$1<b>$2</b>$3');
}
</script>
</head>
<body>
<img src="http://some.web.site/image.jpg" title="abcd"/>
These words are highlighted: knorex, edge, rss feeds while these words are not: knewedge, abcdef, rss feedssss
<input type ="button" value="Button" onclick = "myFunction()">
</body>
</html>
A textNode cannot have child elements so it needs to be replaced, one way;
Replace
children[child].nodeValue = output;
With
var n = document.createElement("span");
n.innerHTML = output;
children[child].parentNode.replaceChild(n, children[child]);

Categories