I dont want anyone to make my homework, i just want to ask if someone can advise me to the right way, before more people put these kind of comments.
I have an assignment where i have to make a webpage with a textbox and a button. The user must put text in the textbox and when pressing the button, it should display in H1. When pressing again it should display in H2, this till H6 and then repeating itself to H1.
The previous assignment asked me to make a Textbox and a Button which only displays the users text in normal letters.
This is the code:
<!DOCTYPE html>
<html lang="nl">
<head>
<title>Paragraaf op tekstvlak.</title>
<script>
var index = 1;
window.onload = function() {
document.getElementById('btnKnop1').onclick = function() {
var newElement = document.createElement('div');
newElementid = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('div-Result').appendChild(newElement);
}
}
</script>
</head>
<body>
<p>Type hier een boodschap die u in de webpagina wilt zetten</p>
<input type="text" id="txtElement"><br>
<button id="btnKnop1">klik hier voor Heads.</button><br>
<div id="div-Result"></div>
</body>
</html>
If someone could give me advise to solve this puzzle and change this code into what the assignment askes me, i would be thankful. I think i need to use a loop, but im not certain how to. The script cannot contain jQuery.
Instead of div you can create h tag, & update the index.So while index is less than 7 you can create the h+index tag. ALso there is no need of window.load if you put the script near the closing end of the body tag
var index = 1;
document.getElementById('btnKnop1').onclick = function() {
if (index < 7) {
var newElement = document.createElement('h' + index);
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
document.getElementById('div-Result').appendChild(newElement);
index++;
}
}
<p>Type hier een boodschap die u in de webpagina wilt zetten</p>
<input type="text" id="txtElement"><br>
<button id="btnKnop1">klik hier voor Heads.</button><br>
<div id="div-Result"></div>
Instead of div you can use h tag. The corrected code is given below,
Instead of div you can create h tag
var index = 1;
document.getElementById('btnKnop1').onclick = function() {
var newElement = document.createElement('h' + index);
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
document.getElementById('div-Result').appendChild(newElement);
index = ++index % 7;
}
<p> Welcome to web designing.</p>
<input type="text" id="txtElement"><br>
<button id="btnKnop1">Change Heading Style</button><br>
<div id="div-Result"></div>
Related
So I want to add to a variable every time someone clicks a button on my website. I am very new to HMTL so I don't know how to do this. All the examples I've googled just change text into other text and not adding to a variable.
If someone would like to enlighten me on how to do this I would greatly apricate it.
function changeIt() {
document.getElementById('test').innerHTML = "<h2>Congrats</h2>";
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
var sum = 0;
function changeIt() {
sum++;
document.getElementById('test').innerHTML = `<h2> ${sum} </h2>`;
}
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()">Test</button>
The code you've written in document.innerHTML is correct. For making it dynamic and to add a new Congrats onto the screen instead of just modifying the old one, you need to keep a global counter and loop over it.
let count = 0;
function changeIt() {
count++;
for (let i=0;i<count;i++) {
document.getElementById('test').innerHTML = '';
let h2 = document.getElementById('test').createElement;
h2.innerHTML = "Congrats";
document.getElementById('test').appendChild(h2);
}
}
Since you are calling the changeIt function on every button click it will let you update the count and will loop over the count to add the Congrats 'count' number of times to your div.
I currently have an array of user inputted words and respective highlight colors stored in objects (below is the function that constructs the array upon user button click and input):
//DECLERATIONS////
var placementId = 0;
var searchList = [];
///FUNCTION THAT ADDS A NEW WORD TO SEARCHLIST////////
function addWord(userWord, userColor){ //append new word to find and highlight
var wordAndColorPair = {
word: userWord,
color: userColor,
id: placementId
}
searchList.push(wordAndColorPair);
}
///////BELOW IS THE EVENT THAT ACTUALLY CONSTRUCTS THE ARRAY//////////
$('.color-element').click(function(){ //adding new word-color pairs
var userInput = $('#input-word').val();
if(userInput !== ''){ //only if user enteres text:
var newWord = document.createElement("span"); //create a new search word tile
newWord.classList.add('search-word'); //add the class search-word to it
newWord.textContent = userInput; //make its text value equal to the input
var colorId = $(this).attr('id'); //set its bacckground color to a copy of the button clicked
$(newWord).css("background-color", colorId);
$(newWord).attr('id', placementId); //set this new elements unique ID for delection purposes
$('.display-array').append(newWord); //append the child to the DOM
addWord(userInput, colorId, placementId); //add the word to the search list - increment placementId for future words
placementId ++;
$('#input-word').val(''); //reset the input field
}
else{
return;
}
});
What I am having trouble with is being able to search the whole page and actually highlight the words seen in the array. What I have so far is:
$('.search').click(function(){ //when the search button is clicked
var i;
for(i =0; i< searchList.length; i++){//for each word user inputted:
$("*").contents().each(function() {
var word = searchList[i].word;
var regex = new RegExp('(\\b'+word+'\\b)', 'gi');
if(this.nodeType == 3){ //if text
$(this).html(text.replace(regex, " <span style = 'background-color: " + searchList[i].color + " ;'> " + searchList[i].word + "</span>"));
}
});
}
});
This, however, does not seem to be working, any assistance is much appreciated!
HTML for DOM reference:
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Changa:700|Roboto+Condensed:700" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Slab" rel="stylesheet">
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type = "text/javascript" src="popup.js"></script>
<meta charset="utf-8">
<title>Word Finder</title>
<link rel="stylesheet" href="style.css" media="screen">
<meta name="description" content="Word Finder Chrome Extension">
<meta name="author" content="Aalok Borkar">
</head>
<body>
<p>
this is a test of the funcitonality TEXT text text text hello
</p>
<div class = "input">
<div class = "word">
Word <input type = "text" id = 'input-word' placeholder= "Jim Halpert"></input>
</div>
<div class = "color-palette">
<!-- on click: clear text input, add color, append search array / display array -->
<button class = "color-element" id = "red"></button>
<button class = "color-element" id = "orange"></button>
<button class = "color-element" id = "yellow"></button>
<button class = "color-element" id = "green"></button>
<button class = "color-element" id = "blue"></button>
<button class = "color-element" id = "violet"></button>
<button class = "color-element" id = "pink"></button>
</div>
</div>
<div class = "display">
<p> Words to Search</p>
<div class = "display-array">
</div>
</div>
<button class = "search">Search</button>
</body>
</html>
It need to be done that way:
$(this).parent().html($(this).parent().html().replace($(this).text(),$(this).text().replace(regex, " <span style = 'background-color: " + searchList[i].color + " ;'>" + searchList[i].word + "</span> ")));
This is because when you change the innerHTML directly you will mess the dom structure and lose the html format, when you change the text solely you would have a a sanitized DOM inside quotes, so it should be solved one way by modifying the text part inside the inner html.
see it here
I added a class to your <p> element, but you probably don't have to do that. I just did it for ease of access on my part. The biggest thing, if I understood your question right, was your search function. IMO, you need to look at each word and compare it to the search array. Find the word that matches and wrap it in something that you can apply a style to. In my case, I chose a <span> tag. Fiddle below code.
// HTML Modification
<p class="searchable">
this is a test of the functionality TEXT text text text hello
</p>
$('.search').click(function() { //when the search button is clicked
var original = $('.searchable').html().trim();
var searchable = original.split(" ");
for (var i = 0; i < searchList.length; i++) { //for each word user
inputted:
for (var s = 0; s < searchable.length; s++) {
if (searchable[s] == searchList[i].word) {
searchable[s] = "<span style='background:" + searchList[i].color +
";'>" + searchList[i].word + "</span>";
}
}
}
rewrite(searchable); //SEE BELOW
});
// This iterates over the searchable array
function rewrite(searchable) {
var highlighted = "";
for (var i = 0; i < searchable.length; i++) {
highlighted += searchable[i] + " ";
}
$('.searchable').html(highlighted.trim());
}
https://jsfiddle.net/5v3aqrzd/
function $(selector) {
var resultObject = {
append: function (element) {
var parser = new DOMParser();
var dos = parser.parseFromString(element, "text/html");
var all = dos.getElementsByTagName("body")[0];
var elemWhichAppend = document.getElementsByTagName(selector);
var children = all.childNodes;
for (var i = elemWhichAppend.length-1; i >=0; i--) {
var msgContainer = document.createDocumentFragment();
var children = all.childNodes;
for (var child = 0; child < children.length; child++) {
var al = children[child];
msgContainer.appendChild(al);
}
insertAfter(msgContainer, elemWhichAppend[i]);
}
}
}
return resultObject;
}
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<script src="jqueryjs.js"></script>
</head>
<body>
<h1 class="testing">APPEND</h1>
<p>Hallo, ich bin ein P TAG </p>
<h1 class="testing">APPEND2</h1>
<p>BADGL</p>
<input type="button" value="append tag/text " onclick="$('p').append('<ul><li>RIBA RIBI<ul><li>FRANK RIBERY</li></ul></li></ul> <h1>NIGOGOG</h1> messi ist scheiße');" />
</body>
</html>
Run code snipped. As you can see the function adds only to the last p element the tags. And forgets the 'messi ist scheiße'. I tried a lot of thinks but I am not able to find my bug. Is it because the 'messi ist scheiße' a text is?
You made this way more complicated than it needs to be. Just make the append function append your string onto the element's innerHTML.
function $(selector) {
var resultObject = {
append: function (element) {
var elemWhichAppend = document.getElementsByTagName(selector);
for (var i = elemWhichAppend.length-1; i >=0; i--) {
elemWhichAppend[i].innerHTML += element;
}
}
}
return resultObject;
}
<h1 class="testing">APPEND</h1>
<p>Hallo, ich bin ein P TAG </p>
<h1 class="testing">APPEND2</h1>
<p>BADGL</p>
<input type="button" value="append tag/text " onclick="$('p').append('<ul><li>RIBA RIBI<ul><li>FRANK RIBERY</li></ul></li></ul> <h1>NIGOGOG</h1> messi ist scheiße');" />
Wrapping (messi ist scheiße) in a div, p or h1 tag will do the trick.
<input type="button" value="append tag/text " onclick="$('p').append('<ul><li>RIBA RIBI<ul><li>FRANK RIBERY</li></ul></li></ul> <h1>NIGOGOG</h1> <p>messi ist scheiße</p>');" />
On testing this a little in JS fiddle, i found that as you loop through the child elements, for some reason the variable you declared as 'all' seems to be dissappearing, or at least deteriorating in nature to the extent that it doesn't contain any child elements on the second loop, and so does not go through the Child-elements loop the second time around.
One thing that seemed to improve performance was redefining all and dos at the top of the loop:
for (var i = elemWhichAppend.length-1; i >=0; i--) {
var dos = parser.parseFromString(element, "text/html");
var all = dos.getElementsByTagName("body")[0];
var msgContainer = document.createDocumentFragment();
...
This should help, as it certainly solved the JSFiddle I was on. I'm not certain why the 'all' variable is changing in nature exactly, but it changes - as i saw from the log - as soon as you perform this line:
msgContainer.appendChild(al);
I imagine it happens after you perform that line because that line actually accesses the 'document' object and causes it to change (since msgContainer is derived from document object).
Also, you would probably have to include the 'messi ist Shiese' into a html tag, as the line
var dos = parser.parseFromString(element, "text/html");
This line seems to only find the HTML elements in the element you've provided. You can check this by trying to console.log the 'child' element itself, and you will see that when you include the 'messi ist sheise' part into a tag, it will appear, but it won't appear when it's not in a tag.
for (var child = 0; child < children.length; child++) {
var al = children[child];
console.log(children[child]);
msgContainer.appendChild(al);
}
You've missed a "" near getElementsByTagName
I am trying to spawn different div's and remove them after they do their job. A simple version of my code is:
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(child);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"?\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>'
The problem is that when the first spawned div is deleted, all div's are deleted. Any help is appreciated on how to fix this.
How about something like this:
function eraseDiv(target){
var div = target.parentNode;
var container = div.parentNode;
container.removeChild(div);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<button onclick=eraseDiv(this);> Delete</button>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<button type="button" name="submit" onclick="spawnDiv();">Spawn</button>
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
First thing, since you're returning false every time you obviously don't want to use the submit functionality of your submit input, so change it to a button instead.
Second thing, remove the ID from the spawned div since you should never have two divs with the same ID.
Third thing (like the first thing) since you're not using the link functionality of the anchor element, you should change it to a button instead (using CSS you can style this like an anchor if you want to).
Fourth thing, inside the delete button, add this as a parameter to the eraseDiv function. You can now access the button that was clicked using the function parameter rather than trying to find it by an ID.
The simplest fix to your code without modifying the functionality (and view of the page) of what you did is to replace the href="?" with href="#".
In your original code, when you do something like link with the "?" as the hyperlink, this actually performs a GET request which will reload the page. This is tricky because it makes it seem like your delete code is removing all the spawned divs from both cn1 and cn2 divs.
Changing the href=? to href=# prevents a GET request from happening. Below is a snippet that directly makes this change that results in the correct behavior of your original code (by deleting the spawned element in cn1). You will have to further modify your code to make it do what you want.
function eraseDiv(){
var c = document.getElementById("cn1");
c.parentNode.removeChild(c);
}
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child";
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<a href=\"#\" onclick=eraseDiv(); return false; > Delete</a>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
Another way of doing it would be to create a id for div like this
<html>
<body>
<input type="submit" name="Submit" value="Spawn" onclick="spawnDiv(); return false;" />
<div id= "test">
<div id= "cn1"></div>
<div id= "cn2"></div>
</div>
<script>
function eraseDiv(j){
var c = document.getElementById('child'+j);
c.parentNode.removeChild(c);
}
var i=1;
function spawnDiv(){
var x = document.getElementById("test");
var d = document.createElement("div");
d.id = "child"+i;
d.style.width = "500px";
d.style.height = "30px";
var content = "Some text for testing!" + "<u ><a onclick=eraseDiv("+i+++"); > Delete</a></u>";
d.innerHTML = content;
if (document.getElementById("cn1").innerHTML.trim() == "")
document.getElementById("cn1").appendChild(d);
else
document.getElementById("cn2").appendChild(d);
}
</script>
</body>
</html>
I wish to know the best way to write only once the same thing and repeat inside the same page. For example:
<div>
<p id="description1"></p>
</div>
<div>
<p id="description1"></p>
</div>
--
I wish to write only one time the description1 inside the body. I think this could be achieved using the DOM.
Put the elements in the same class using the class attribute, then get the list of all elements using the getElementsByClassName() DOM function. You can then go over the list using a for loop.
[].forEach.call(document.getElementsByClassName("description"), function(elem) {
elem.innerHTML = "StackOverflow saved my day!";
});
You can even put the text in all elements of the same class using no JavaScript and only CSS by using the content attribute.
First of all, the ID field should be unique per element.
If you give all the tags a class <p class="description"></p> then you can use jQuery to set them all by calling:
$('.description').text('This is the text')
In javascript:
var elements = document.getElementsByClassName("description");
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "This is the text.";
}
Have a look at the solutions proposed here
How to repeat div using jQuery or JavaScript?
this one seems to work pretty well:
html:
<div id="container">data</div>
js:
var container = document.getElementById('container');
function block(mClass, html) {
//extra html you want to store.
return '<div class="' + mClass + '">' + html + '</div>';
}
// code that loops and makes the blocks.
// first part: creates var i
// second: condition, if 'i' is still smaller than three, then loop.
// third part: increment i by 1;
for (var i = 0; i < 3; i++) {
// append the result of function 'block()' to the innerHTML
// of the container.
container.innerHTML += block('block', 'data');
}
JSFIDDLE
Just added with a code by using
getElementsByClassName()
`<html>
<body>
<div class="example">First div element with class="example".</div>
<p class="example">Second paragraph element with class="example".</p>
<p>Click the button to change the text of the first div element with class="example" (index 0).</p>
<button onclick="myFunction()">Try it</button>
<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
for(var i=0;i< x.length;i++)
x[i].innerHTML = "Hello World!";
}
</script>
</body>
</html>`
If you wish to keep id, change your code like this :
script :
var pcount = 2// # p
var desc = document.getElementById('description1');
for(i=0; i<pcount;i++){
document.getElementById('description' + i).innerHTML = desc;
}
html
<div>
<p id="description1"></p>
</div>
<div>
<p id="description2"></p>
</div>
two elements cannot have same id but can have same class
<head>
<script>
var x = document.getElementsByClassName("description");
for (var i = 0; i < x.length; i++) {
x[i].innerHTML = "This is the text.";
}
</script>
<style>
.description1 { // this will apply the same style to all elements having class as description1
text-align: center;
color: red;
}
</style>
</head>
<body>
<div>
<p class="description1"></p>
</div>
<div>
<p class="description1"></p>
</div>
</body>
See the script tag. this solves your problem