Javascript: My .textContent works, but not my innerHTML - javascript

I have a strange problem. In general, when I set a variable as textContent, it shows it, but it doesn't when I set it as innerHTML
More precisely
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Dynamic Menu</title>
</head>
<body id="top">
<h1>The Extremadura Region of Western Spain</h1>
<h2 >Geography Of The Region</h2>
<p>The autonomous community of Extremadura is in western Spain alongside the Portuguese border.
It borders the Spanish regions of Castilla y Leon, Castilla La Mancha and Andalucía as well as Portugal (to the West).
Covering over 40,000 square kilometers it has two provinces: Cáceres in the North and Badajoz in the South.</p>
<h2>Where To Stay</h2>
<p>There is a wide range of accommodation throughout Extremadura including small inns and guest houses ('Hostals') or
think about renting a 'casa rural' (country house) if you are travelling in a group.</p>
<h2>Climate</h2>
<p>Generally Mediterranean, except for the north, where it is continental. Generally known for its extremes,
including very hot and dry summers with frequent droughts, and its long and mild winters.</p>
<h2>What To See</h2>
<p>Extremadura hosts major events all year round including theater, music, cinema, literature and folklore.
Spectacular venues include castles, medieval town squares and historic centers.
There are special summer theater festivals in the Mérida, Cáceres, Alcántara and Alburquerque.</p>
<h2>Gastronomy</h2>
<p>The quality of Extremaduran food arises from the fine quality of the local ingredients.
In addition to free-range lamb and beef, fabulous cheeses, red and white wines, olive oil, honey and paprika,
Extremadura is particularly renowned for Iberian ham. The 'pata negra' (blackfoot) pigs are fed on acorns in the
cork-oak forests, the key to producing the world's best ham and cured sausages.</p>
<script src="lunch.js"></script>
</body>
</html>
Here is the script
function lop(){
var hs = document.getElementsByTagName('h2');
for(var g = 0; g<hs.length; g++){
hs[g].setAttribute('id', g);
}
var budy = document.getElementById('top'); //Gets the body id
var nnn = document.createElement('nav'); //Creats a nav event
var uuu = "<ul > \
<li id='one'> <a href='#0'>Geography Of The Region </a> </li> \
<li id='two'> <a href='#1'>Where To Stay </a> </li> \
<li id='tre'> <a href='#2'>Climate </a> </li> \
<li id='for'> <a href='#3'>What To See</a> </li> \
<li id='fiv'> <a href='#4'>Gastronomy</a> </li>";
// li: 55-60 make the HTML
nnn.innerHTML = uuu; //Sets the HTML to the nav
var h = document.getElementsByTagName('h2')[0]; // Get the specific element
budy.insertBefore(nnn, h); // inserts the element nav and the whole html before h
var ps = document.getElementsByTagName('p');
var hih = ' AAAAA ';
for(var g = 0; g<ps.length; g++){
ps[g].nextSibling.innerText = hih;
}
}
lop(); //cals the function so it executes
So basicly in this exercise i have to create an ul within the script and without modyfing the HTML.
I successed in creating an ul. Then I have to creat a link that brings me to the top of the page. Which is this part here:
var ps = document.getElementsByTagName('p');
var hih = ' AAAAA ';
for(var g = 0; g<ps.length; g++){
ps[g].nextSibling.innerText = hih;
}
Here I try to creat a link that bring me back to the top. Im using the advantage that chrome has blank space betwwen sibling to creat that link in there.
The problem is that it doesn't show. When I go to my debugger, I have no errors, but nothings shows. If change ps[g].nextSibling.innerText = hih; for .textContent it shows the whole think.
I know the difference between .innerHTML and .textContent (or I think), so why doesn't it show my link and can I make it show ?

I don't understand you use nextSibling. If you want to use innerHTML, you can use bellow script
ps[g].innerHTML = ps[g].innerHTML + hih;
You can read about nextSibling in https://www.w3schools.com/jsref/prop_node_nextsibling.asp

Ok so a friend of mine changed my procedure and here what he did:
var ps = document.getElementsByTagName('p');
var hih = '<br /><br /> To the top ';
for(var g = 0; g<ps.length; g++) {
ps[g].innerHTML += hih;
}
In other words, what I learned from this 3h of js, is that you can't change a blank child's HTML, but only his text.

Related

DOM Methods get the right element from a Node - Using only JavaScript

I am doing an exercise, but I am stuck. I need to get the first line of each paragraph after each "H4", but at the moment it is getting all the "P" from the first "H4".
I got an HTML and a JavaScript, the idea is to get a news summary after Bizarre News Summary, I have created the 'UL', 'LI' and appended them
function newsSnippets() {
let classNewsarticle = document.getElementsByClassName("newsarticle"); // Get classes by name 'newsarticle'
let headlinesId = document.getElementById("headlines"); // Get Id 'headlines'
let newsSummary = document.createElement("div"); // Create DIV
headlinesId.appendChild(newsSummary); // Append headlines to DIV
let newsSummaryList = document.createElement("ul"); // Create UL
newsSummary.appendChild(newsSummaryList); // Append UL to DIV
console.log(classNewsarticle);
for (let i = 0; i < classNewsarticle.length; i++) {
let newsSummaryListItem = document.createElement("LI"); // Create an LI for each H4
newsSummaryList.appendChild(newsSummaryListItem); // Append the LI to the UL
let getH4 = document.getElementsByTagName("H4")[i].childNodes[0].nodeValue;
let getH4Node = document.createTextNode(getH4);
let ellipsis = document.createTextNode(" . . . ");
let p = document.getElementsByTagName("P")[i].innerHTML;
let pNode = document.createTextNode(p);
newsSummaryListItem.appendChild(getH4Node) + // Append the texts node to the LI element
newsSummaryListItem.appendChild(ellipsis) +
newsSummaryListItem.appendChild(pNode);
let newsList = document.createElement("LI"); // Create the inline text anchor
document.body.insertBefore(newsList, newsSnippets[i]); // Insert the text anchor before headings
}
}
window.onload = newsSnippets;
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript</title>
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<script src="scripts/fma_t1.3.js"></script>
</head>
<body>
<div id="wrappermain">
<h1>Bizarre News Mash Up</h1>
<section id="headlines">
<h2>Bizarre News Summary</h2>
</section>
<section id="news">
<h3>News Stories in Full</h3>
<article class="newsarticle">
<h4>What a load of Bull!</h4>
<p>Chinese Kung Fu Masters are seeking the ultimate opponents</p>
<p>Several times a week, kung fu teacher Ren Ruzhi enters a ring to spar with a bovine opponent around five times his weight and capable of killing him.</p>
<p>Ren’s mixing of martial arts and bullfighting worries his mother, but the 24-year-old has never been hurt. Besides, he says, grappling with a snorting bull is exciting.</p>
<p>It symbolizes the bravery of a man,” Ren told Reuters in Jiaxing in China’s eastern province of Zhejiang.</P>
</article>
<article class="newsarticle">
<h4>Has Anybody got a Tissue?</h4>
<p>A Hawaiian monk seal got an eel caught in its nose ― and it wasn’t the first time for these endangered creatures.</p>
<p>The Hawaiian Monk Seal Research Program posted a startling pic of the poor pup on Monday, and the National Oceanic and Atmospheric Administration Fisheries provided more details in a post on Wednesday.</p>
</article>
<article class="newsarticle">
<h4>Dog Pulls Off Spectacular Save During Argentina Soccer Match</h4>
<p>A pooch invaded the pitch during a Federal A league match between Juventud Unida and Defensores de Belgrano over the weekend.</p>
<p>Juventud Unida were already comfortably ahead against Defensores de Belgrano in their league clash when the dog made his unexpected cameo.</p>
</article>
<article class="newsarticle">
<h4>Nobody Beats The Laws of Nature</h4>
<p>A 69-year-old Dutch man has failed in his attempt to legally declare himself 20 years younger.</p>
<p>Last month, motivational speaker Emile Ratelband filed a lawsuit against the Dutch government requesting that his date of birth be switched from March 11, 1949, to March 11, 1969.</p>
</article>
</section>
</div>
<!-- Stories from Huffington Post. Used for Teaching purposes -->
</body>
</html>
This seems a little too complicated. If you are allowed to, try something like this:
function newsSnippets() {
const results = document.evaluate('//article[#class="newsarticle"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
let temp = "<div><ul>"
for (let i = 0; i < results.snapshotLength; i++) {
let node = results.snapshotItem(i);
let new_item = "<li>"+node.querySelector('h4').innerText+ '...' +node.querySelector('p').innerText+"</li>";
temp += new_item;
}
temp += "</ul></div>"
let target = document.querySelector('section#headlines');
target.insertAdjacentHTML('beforeend', temp);
}
I was able to came up with an answer myself and it works just fine.
function newsSnippets() {
let classNewsarticle = document.getElementsByClassName("newsarticle"); // Get classes by name 'newsarticle'
let headlinesId = document.getElementById("headlines"); // Get Id 'headlines'
let newsSummary = document.createElement("div"); // Create DIV
headlinesId.appendChild(newsSummary); // Append headlines to DIV
let newsSummaryList = document.createElement("ul"); // Create UL
newsSummary.appendChild(newsSummaryList); // Append UL to DIV
for (let i = 0; i < classNewsarticle.length; i++) {
let newsSummaryListItem = document.createElement("LI"); // Create an LI for each H4
newsSummaryList.appendChild(newsSummaryListItem); // Append the LI to the UL
let getH4 = document.getElementsByTagName("H4")[i]; // Get H4s
let getH4Text = getH4.childNodes[0].nodeValue; // Get H4s Nodes
let getH4Node = document.createTextNode(getH4Text); // Get H4s HTML Text
let ellipsis = document.createTextNode(" . . . "); // Create Text Node Ellipsis
let p = getH4.nextElementSibling.innerHTML; // Get P as the Next Element Sibling from each H4
let pText = document.createTextNode(p); // Create Text Node for each first P after H4
newsSummaryListItem.appendChild(getH4Node) + // Append the textNodes to the LI element
newsSummaryListItem.appendChild(ellipsis) +
newsSummaryListItem.appendChild(pText);
}
}
window.onload = newsSnippets;

Highlighting text content using the content from an another div

I want to highlight the text content in paragraph using text content from an another div. So there is the "increase overall code" in the the first div. I want that these words from the main paragraph to be highlighted by using the first div. Thank you for the possibility to ask for help here!
function highlight() {
var htext = document.getElementById("torles");
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text);
if (index >= 0) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
innerHTML.innerHTML = innerHTML;
}
}
.highlight {
background-color: red;
}
<html>
<body>
<div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder
</div>
<button onclick="highlight()">Highlight</button>
<div class="col-md-10 para bordered" id="inputText">
<strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
</div>
</body>
</html>
So, there were a couple things; but first, here's a working example.
function highlight() {
var text = document.getElementById("torles").textContent;//you want the text not the node
var inputText = document.getElementById("inputText");
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text);
if (index >= 0) {
innerHTML = innerHTML.substring(0, index) + "<span class='highlight'>" + innerHTML.substring(index, index + text.length) + "</span>" + innerHTML.substring(index + text.length);
inputText.innerHTML = innerHTML;//this line was incorrect
}
}
.highlight {
background-color: red;
}
<html>
<body>
<div class="col-md-10 bordered selectborder fragment" id="torles">increase overall coder</div><!-- make sure there's no line break after "coder"-->
<button onclick="highlight()">Highlight</button>
<div class="col-md-10 para bordered" id="inputText">
<strong><p>Significantly Reduce Costs and Improve Quality with an Experienced, Professional Global Coding Solution. Health Information Management (HIM) Directors and CFOs are seeking innovative ways to reduce expenses, maintain DNFB goals, and increase overall coder quality.</p></strong>
</div>
</body>
</html>
Anyway, there were three main things (and a typo). Firstly, you had a line break in your HTML after increase overall coder, and so it would try to find that string with the line break in the text, so it would just not find it.
Second, you mixed up what your variables actually mean; to start off, the text variable (which you misspelled as htext) was a node, not a string. Also, you tried to set the innerHTML of innerHTML, but your variable innerHTML was just a string. You want to set the innerHTML of the node (inputText in this case).

Add New Line in textarea by getElementById().value not Working

I'm quite new in Javascript. Sorry if I say some absurd. None of the previous answers I found here worked in my case...
The code gets an index from a selected option from a dropdown list generated by an array loop, and uses this index to post description of a product in a textarea. Ideal would be one in each line. But whenever I add '\n'(added only for visualization by the end of the code) or '
&#10'; the dropdown list itself disapears. Trying '< br>' does not work either.
pr[] is a nested array that contains a description of 10 products (ex adidas soccer ball) in its first position and price at the second.
The function buy() is called by a button onclick event, each time it is called it adds one product to the textarea.
Thanks in advance!
textd=" ";
valord=0;
function buy() {
var e = document.getElementsByTagName("select");
var f = e[0].selectedIndex;
textd +=pr[f][0];
valore = valord += pr[f][1];
document.getElementById("compras").value=textd\n;
document.getElementById("valor").value ="R$ "+ valore+",00";
}
You need to add "\n" to the end of the string while adding text to text area, then this "\n" ensures that row will be displayed in a new line instead of same line.
Look at the following code
<!DOCTYPE html>
<html>
<body>
<script>
function appendText()
{
debugger;
var ele = document.getElementById("textArea");
var text = ele.value;
text += "im clicked\n";
text +="clicked again\n";
text +="clicked third time\n";
text +="clicked forth time";
ele.value = text;
}
</script>
<textarea rows="4" cols="50" id="textArea">
At w3schools.com you will learn how to make a website. We offer free tutorials in all web development technologies.
</textarea>
<button type="button" onclick="appendText()">Click me </button>
</body>
</html>
You may need to change your code to
textd +=pr[f][0] + "\n";
document.getElementById("compras").value=textd;

Not printing "id" when called in HTML from JavaScript

I am working on an assignment where I have to pull quote and a name from a randomized array of such and display them in my HTML page. under some filler text. For what ever reason the script is running and displaying a different id (a simple local date a time display) but not the quote randomizer. Any help would be greatly appreciated.
HTML
</head>
<body>
<h1>CIS - 16W</h1>
<nav id="nav">
<ul>
<li>Home</li>
<li>Assignment 2</li>
<li>Assignment 3</li>
<li>Assignment 4</li>
<li>Assignment 5</li>
<li>Assignment 6</li>
<li>Assignment 7</li>
<li>Final Project</li>
</ul>
</nav>
</body>
<meta charset="utf-8">
<meta name=“description” content=“description”>
<meta name=“author” content=“your”>
<link rel="stylesheet" href="../css/styles.css">
<script src="../functions.js"></script>
<main>
<p>My name is _____ and I am a junior here at the _____.<br>I'm very excited to get started and hone in my skills in the multimedia environment!
</p>
<p>I am taking this course to help not only fill the math requirment for a Bacholer of Science, but also to aid my Multimedia minor and Advertising major!</p>
<span id="quote"></span>
<span id="name"></span>
JavaScript
window.onload = function () {
setInterval(timeAndDate, 1000);
}
var quotes = ["\"How many cares one loses when one decides not to be something but to be someone.\"",
"\"If you want to test a man's character give him power.\"",
"\"I just hope that one day, perferably when we're both blind drunk, we can talk about it\"",
"\"Why do you look so sad?'<br>'Because you speak to me in words and I look at you with feelings.\"",
"\"Courage is what it takes to stand up and speak. Courage is also what it takes to sit down and listen.\""];
var names = ["-Coco Chanel", "-Abrham Lincoln", "-J. D. Salinger", "-Leo Tolstoy", "-Wiston Churchill"];
var arrIndex = Math.floor(Math.random() * (quotes.length));
function quoteGen() {
var quoteAll = document.getElementById("quote");
var namesAll = document.getElementById("name");
quoteAll.innerHTML = quotes[arrIndex];
namesAll.innerHTML = names[arrIndex];
if (arrIndex > quotes.length-1) {
arrIndex = 0;
}
}
function timeAndDate() {
var date = new Date();
var n = date.toDateString();
var time = date.toLocaleTimeString();
document.getElementById('localDate').innerHTML = n + ' ' + time;
}
There are 2 problems here,
You are not calling quoteGen which is updating the quotes, the timer need to call quoteGen but you are calling timeAndDate that is why the timing is getting updated, not the quotes
You need to generate the random index within quoteGen so that every invocation will get a new random value
window.onload = function() {
setInterval(quoteGen, 1000);
}
var quotes = ["\"How many cares one loses when one decides not to be something but to be someone.\"",
"\"If you want to test a man's character give him power.\"",
"\"I just hope that one day, perferably when we're both blind drunk, we can talk about it\"",
"\"Why do you look so sad?'<br>'Because you speak to me in words and I look at you with feelings.\"",
"\"Courage is what it takes to stand up and speak. Courage is also what it takes to sit down and listen.\""
];
var names = ["-Coco Chanel", "-Abrham Lincoln", "-J. D. Salinger", "-Leo Tolstoy", "-Wiston Churchill"];
var idx;
function quoteGen() {
//the looping is used to make sure that every call to quoteGen will update a new quote
do {
var arrIndex = Math.floor(Math.random() * (quotes.length));
} while (idx == arrIndex);
idx = arrIndex;
var quoteAll = document.getElementById("quote");
var namesAll = document.getElementById("name");
quoteAll.innerHTML = quotes[arrIndex];
namesAll.innerHTML = names[arrIndex];
}
<p>My name is _____ and I am a junior here at the _____.
<br>I'm very excited to get started and hone in my skills in the multimedia environment!
</p>
<p>I am taking this course to help not only fill the math requirment for a Bacholer of Science, but also to aid my Multimedia minor and Advertising major!</p>
<span id="quote"></span>
<span id="name"></span>
You are not calling quoteGen() anywhere.

Create html element with jquery based on user input

So after searching a while I haven't been able to find an existing question that seems to address this in a way that I can relate to with my specific issue. If there is already a good thread on this that I missed, my apologies in advance and feel free to just post a link to it and call me a dummy!
In plain english, here's the goal: I basically want to generate some html with jquery but with a couple of twists. There will basically be two sets of content that will alternate with every other number, I'll call them content-a and content-b. The user is prompted to enter a number, let's say user enters 4. Upon submitting this value, the markup is then generated like so: (1)content-a (2)content-b (3)content-a (4)content-b.
So here's a bit of code that hopefully will help a little.
I'm aware of how to generate html, but that's about as far as I've gotten so far, my js is definitely a weak point and needs lots of practice:
$("#targetDIV").html("<h1>Hello World!</h1> <p>This is a big fat test</p>");
The markup is simple enough, almost seems pointless to post it in here since it's kind of obvious but I'll do it anyway:
<div id="targetDIV" style="border: 3px solid purple">
</div>
The desired output though would be something like this, based on the value the user chooses but let's just stick with the 4 example:
<div id="targetDIV" style="border: 3px solid purple">
<!-- Content A -->
<h1>Hello World!</h1>
<p>This is a big fat test</p>
<!-- Content B -->
<h1>Hello Universe!</h1>
<p>This is a super mega big fat test</p>
<!-- Content A -->
<h1>Hello World!</h1>
<p>This is a big fat test</p>
<!-- Content B -->
<h1>Hello Universe!</h1>
<p>This is a super mega big fat test</p>
</div>
Hopefully there's enough here to go on or to at least point me in the right direction, thanks in advance for any wisdom any of you might offer up!
Here is a full, working live example that does exactly what you're looking for.
The following code will take a numerical input from the user, then append alternating sets of content according to the number the user inputted:
var num = prompt("Enter a number");
var contenta = "<h1>Hello World!</h1> <p>This is a big fat test</p>";
var contentb = "<h1>Hello Universe!</h1> <p>This is a super mega big fat test</p>";
var targetDiv = $("#targetDIV");
console.log(targetDiv);
for (var i = 0; i < num; i++) {
if (i % 2 === 0) targetDiv.append(contenta);
else targetDiv.append(contentb);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="targetDIV" style="border: 3px solid purple">
</div>
You could assign the two html strings to the indices of an array.
var str1 = "<h1>Hello World!</h1> <p>This is a big fat test</p>"
var str2 = "<h1>Hello Universe!</h1> <p>This is a super mega big fat test</p>"
var responses = [str1, str2];
Then, you can use a for loop that will repeat as many times as the user's input.
And in each iteration of the loop, you could perhaps $('#targetDIV').append(responses[i % 2]);
You could do something like this.
$('#number').change(function() {
var ind = $(this).val()
$('#target-div').append($('#holder div').get(ind))
});
This keeps the HTML in a hidden div, then extracts your desired content by its index. Not the best way but works.
JSFiddle
If you are simply alternating between two content sets, you can simply store them as a JS array, say content, and generate/insert them on the fly.
The key is to empty your target element when the user updates the change count, and access the correct element in the array based on the modulus of the array size, i.e. content[i%content.length]. This method allows you to arbitarily increase the size of your content array, and the script will keep inserting elements by going through the list, and repeat from the start when it reaches the end.
$(function() {
var content = [
'<h1>Hello World!</h1> <p>This is a big fat test</p>',
'<h1>Hello Universe!</h1><p>This is a super mega big fat test</p>'
];
$('#count').on('change', function() {
$('#targetDIV').empty();
var count = parseInt($(this).val());
for (var i = 0; i < count; i++) {
$('#targetDIV').append(content[i%content.length]);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="count" type="number" min="0" step="1" value="0" placeholder="0" />
<div id="targetDIV" style="border: 3px solid purple"></div>
I am not an expert js dev but cooked something quick and easy for you.
link to codepen:http://codepen.io/anon/pen/OVdMow
$(function() {
var A = '<!-- Content A --><h1>Hello World!</h1><p>This is a big fat test</p>';
var B = '<!-- Content B --><h1>Hello Universe!</h1><p>This is a super mega big fat test</p>';
var targetDiv = $('#targetDIV');
$('#listCount').on('input', function() {
targetDiv.empty();
for(var i = 0; i < +this.value; i++) {
targetDiv.append( i % 2 == 0 ? A : B );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" name="listCount" id="listCount"/>
<div id="targetDIV" style="border: 3px solid purple">
</div>
function generateElments() {
var num = $("#numOfElements").val();
var writeA = true;
var aElement = "<p>I am <strong>A</strong>!</p>";
var bElement = "<p>I am <strong>B</strong>!</p>";
for (var i = 0; i < num; i++) {
$("#elements-container").append(writeA ? aElement : bElement);
writeA = !writeA;
};
};
Here is a working plunker of what you need!
http://plnkr.co/edit/qI1LtBwDwu7KIKFzUehB?p=preview

Categories