<div id="wpq2">
<div class="subClass">
<a id="linkTO" class="subClass">New Item</a>
or
<a class="subClass">edit</a>
this list
</div>
</div>
i want to hide all the thing except
<a id="linkTO" class="subClass">New Item</a>
I do not have access to html ,
i have to use javascript
i tried somthing
var parentID = document.getElementById('wpq2');
var sub = parentID.getElementsByClassName('subClass');
var lastChild = sub[0].lastChild;
lastChild.style.display = 'none';
Using javascript no idea how to do
Please suggest
Try this instead:
var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get all the a elements
var subs = innerDiv.getElementsByClassName('subClass');
//This will hide all matching elements except the first one
for(var i = 1; i < subs.length; i++){
var a = subs[i];
a.style.display = 'none';
}
Here is a working example
EDIT: The above will only hide the a element, as your text elements are not contained within specific elements then it becomes more tricky. If you are happy to effectively "delete" the HTML you don't want then you can do the following:
var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get the HTML for the a element to keep
var a = innerDiv.getElementsByClassName('subClass')[0].outerHTML;
//replace the HTML contents of the inner DIV with the element to keep
innerDiv.innerHTML = a;
Here is an example
insert new html if you don't need the rest
document.getElementById('wpq2').innerHTML = '<a id="linkTO" class="subClass">New Item</a>';
var parentID = document.getElementById('wpq2');
var innerDiv = parentID.getElementsByClassName('subClass')[0];
var subs = innerDiv.getElementsByClassName('subClass');
subs.forEach(function (sub) { sub.style.display = 'none'; });
document.getElementById("linkTO").style.display = 'block';
Related
I have two buttons SHOW and HIDE. When show is clicked numbers will appear (which are json files, each json file contain only one number 1, 2, 3..) when HIDE is clicked first number(json) in a row dissapear. For example we clicked SHOW button 3 times and got this: 1 2 3 and then clicked HIDE once then we got: 2 3 shown. My problem is when HIDE is clicked I want to save that hidden number by showing it in my div where id="nome". After another clicking on button HIDE another hidden number is shown and old is deleted from div. I tried this:
var pageCounter = 1;
var pageCounterr = 1;
var animalContainer = document.getElementById("animal-info");
var animalContainerr = document.getElementById("nome");
var btn = document.getElementById("btn");
var btnn = document.getElementById("btnn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET','http://10.0.9.243/animals-'+ pageCounter + '.json');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
};
ourRequest.send();
pageCounter++;
});
function renderHTML(data) {
var htmlString = document.createElement("div");
for (i=0; i < data.length; i++){
let pText = document.createTextNode(data[i].name);
let pElement = document.createElement("p");
pElement.append(pText);
htmlString.append(pElement);
htmlString.classList.add('containers') // new Line added
}
animalContainer.append(htmlString);
}
btnn.addEventListener("click", function(){
let containers = document.getElementsByClassName('containers');
if(containers.length > 0){
document.getElementById("nome").innerHTML = containers[0];
containers[0].remove();
}
});
<button id="btn">SHOW</button>
<button id="btnn">HIDE</button>
<h2>Numbers:</h2>
<div id="animal-info"></div>
<h2>Hidden number is:</h2>
<div id="nome"></div>
And what I get as a result is ' [object HTMLDivElement] ' in div with id="nome".
The only thing that is wrong is the used logic, look this:
When you get elements by class name "container" you are getting a array of this:
var htmlString = document.createElement("div");
Cause you defined that element's class to:
htmlString.classList.add('containers')
Then you're just getting div.
Solution:
Inside of this element you have a "p" element, and inside it you have a textNode with the content that you want!
Simple, good programming for you.
I am totally new at javascript and am trying to create a dynamic list in JavaScript that is both a hyperlink to and shows the text string of a tag in my html code that has the id = v1. Kind of like a menu to different parts of that same webpage.
I have tried to do this using document fragments (https://developer.mozilla.org/en-US/docs/Learn/HTML/Introduction_to_HTML/Creating_hyperlinks#document_fragments) but it is not working and I don't have any idea of how to insert the text string of the in the "menu".
Here is part of my code:
var container = document.getElementById("contentarea");
var header = document.getElementById("v1");
for (i = 0; i < length.header; i++) {
$(document.createElement("li")).li;
$(document.createElement("a")).link.append(li)( {
href: "#v1"
})
list.appendChild(li);
container.appendChild(list)
}
You could do something like this
// div to get the textContent from, replace it with whatever you want
const divE = document.getElementById('test');
// our list tag
const list = document.getElementById('list');
// looping
for (let i = 0; i < 4; i++) {
const listEl = document.createElement('li'); // our list element
const aTag = document.createElement('a'); // a new <a> tag to append link
const linkTag = document.createElement('link'); //new link tag
linkTag.href = '#test'; // setting hyperlink
aTag.textContent = divE.textContent // setting the textContent for <a> tag
aTag.appendChild(linkTag); // appending link to the a tag
listEl.appendChild(aTag); // appending a tag to the <li> tag
list.appendChild(listEl) // finally appending our list element to the main list
}
<div id="test">Something here</div>
<ul id="list"></ul>
I am trying to convert this HTML code to be generated by Javascript on the fly for live data.
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
Ive found a few methods like: appendChild, getElementById, innerHTML and so on. Here is what I've tried so far. I can't seem to get the data to show up.
stringy = data2.Items[0].groupName.values[i];
var para = document.createElement("div");
var node = document.createTextNode(stringy);
para.appendChild(node);
var element = document.getElementById("parental");
element.appendChild(para);
//create div and give it a class
para.setAttribute('class', 'dropbtn');
var div = document.createElement("div");
div.setAttribute('class', 'dropdown-content');
para.parentNode.insertBefore(div, para.nextSibling);
//create link tags and give them text
var alinky = document.createElement("a");
alinky.setAttribute('id', 'linky');
document.getElementById('linky').innerHTML = "linky poo"
div.appendChild(alinky);
Hopefully someone could fill in the blanks on getting this HTML code to be reproduced with javascript. Thanks in advance!
EDIT:
I am trying to create a dropdown menu like this:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_js_dropdown_hover
However, I am trying to create multiple dropdown menus, that dynamically change in quantity based on a query to DynamoDB (AWS). therefore I am using javascript to create the html tags.
The problem is that the scope of the query function does not allow me to see the data outside of the query function, or even inject data into it.
For example, if I try to get a button description from the query, and write to it descriptionArray[0] = data2.Items[0].description; so that I can append the button to the dropdown div, it doesn't know which iteration I'm on in the for loop due to scope. In this example, descriptionArray[0] will work, but descriptionArray[i] will not work because the for loop is outside the query.
Here is the entire logic:
//group data
var length = data2.Items[0].groupName.values.length;
// create elements
const dpdown1 = document.createElement('div');
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
console.log(dpdown1);
var button = new Array();
var dpdown2 = new Array();
var membersArray = new Array();
var descriptionArray = new Array();
var linksArray = new Array();
var stringy = new Array;
//list groups
for(i = 0; i<length; i++){
// create button, set button attribs
button[i] = document.createElement('button');
button[i].setAttribute('class','dropbtn');
//create dropdown div, set attributes
dpdown2[i] = document.createElement('div');
dpdown2[i].setAttribute('class', 'dropdown-content');
//list of group names
stringy[i] = data2.Items[0].groupName.values[i];
var stringyy = stringy[i];
var desc;
//query group members and description
var docClient1 = new AWS.DynamoDB.DocumentClient({ region: AWS.config.region });
var identityId = AWS.config.credentials.identityId;
var paramsyy = {
ExpressionAttributeValues: {
":v1": stringyy
},
KeyConditionExpression: "groupName = :v1",
TableName: "group"
};
docClient1.query(paramsyy, function(err, data2) {
if (err) {
console.error(err);
}else{
descriptionArray[0] = data2.Items[0].description;
//traverse members
for(k = 0; k<data2.Items[0].members.values.length; k++){
// create dropdown links of members
membersArray[k] = data2.Items[0].members.values[k];
linksArray[k] = document.createElement('a');
linksArray[k].setAttribute('href', '#')
linksArray[k].innerText = membersArray[k];
// nest into dpdown2 div, set dpdown2 attribs
dpdown2[0].appendChild(linksArray[k]);
}
}
});
button[i].innerText = stringyy + ": " + descriptionArray[0];
// nest into dpdown1
dpdown1.appendChild(button[i]);
dpdown1.appendChild(dpdown2[i]);
}
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
if I use the I from the first for loop inside the query function, it will give me undefined results.
here's how you can do it with vanilla JavaScipt, there are multiple ways to do it, but this way only uses 4 methods: createElement, setAttribute, appendChild, and getElementById, and directly sets 1 property: innerText.
// create elements
const dpdown1 = document.createElement('div');
const button = document.createElement('button');
const dpdown2 = document.createElement('div');
const link1 = document.createElement('a');
const link2 = document.createElement('a');
const link3 = document.createElement('a');
// set link attribs
link1.setAttribute('href', '#')
link1.innerText = 'Link 1';
link2.setAttribute('href', '#')
link2.innerText = 'Link 2';
link3.setAttribute('href', '#')
link3.innerText = 'Link 3';
// nest into dpdown2, set dpdown2 attribs
dpdown2.appendChild(link1);
dpdown2.appendChild(link2);
dpdown2.appendChild(link3);
dpdown2.setAttribute('class', 'dropdown-content');
// set button attribs
button.setAttribute('class','dropbtn');
button.innerText = "Dropdown"
// nest into dpdown1
dpdown1.appendChild(button);
dpdown1.appendChild(dpdown2);
// set dpdown1 class
dpdown1.setAttribute('class', 'dropdown');
// append to DOM
const target = document.getElementById('target');
target.appendChild(dpdown1);
<div id="target"></div>
You will to append it to something, in this example it's <div id="target"></div> but it could be something else.
Happy coding!
Mainly you are just doing things out of order.
Create the .dropdown <div> with its class.
Complete the .dropbtn <button> with its class and text.
Add the button to the div.
Create the .dropdown-content <div>.
Complete each link with its href attribute and text.
Add each link to the .dropdown-content <div>.
Add the .dropdown-content div to the .dropdown <div>.
Find the parent element in the document.
Append the whole complete .dropdown <div> to the document.
var para = document.createElement("div"); //make .dropdown div
para.setAttribute('class', 'dropdown'); //add .dropdown class to div
var button = document.createElement("button"); //create button
button.setAttribute('class', 'dropbtn'); //add .dropbtn class to button
var node = document.createTextNode('Dropdown'); //create button text
button.appendChild(node); //add text to button
para.appendChild(button); //add button to .dropdown div
var div = document.createElement("div"); //create .dropdown-content div
div.setAttribute('class', 'dropdown-content'); //add .dropdown-content class to div
//repeat for all necessary links
var alinky = document.createElement("a"); //creat link
alinky.setAttribute('href', '#'); //set link href attribute
var alinkyText = document.createTextNode("Link 1"); //create text for link
alinky.appendChild(alinkyText); //add text to link
div.appendChild(alinky); //add link to dropdown div
para.appendChild(div); //add .dropdown-content div to .dropdown div
var element = document.getElementById("parental"); //find parent element
element.parentNode.insertBefore(para, element.nextSibling); //add .dropdown div to the bottom of the parent element
<div id="parental">
</div>
I have an HTML document with 6 Divs, I've written a javascript code that changes the heading depending on which div is selected (6 vars and 6 functions) e.g.
var divSelect = document.getElementById("firstDiv");
divSelect.onclick = function () {
var mainHeading = document.getElementById("heading");
mainHeading.innerHTML = "You have selected the first option";
};
I then have an anchor div which is linking to another HTML page, when it opens I want it to know which div was selected from the first HTML page, and then input a new heading based on the selection.
So I need to know which of the six functions was actioned based on the div that was clicked.
Any help much appreciated.
You can pass it in url query. Passing for example id parameter, like this: http://example.com/secondpage.html?firstpagedivid=firstDiv And then on second page you can parse url to get div id or whatever parameter you passed.
Here you can find how to get url parameter on second page: link
Html:
<div class="clickable" id="firstDiv">first</div>
<div class="clickable" id="secondDiv">second</div>
<div class="clickable" id="thirdDiv">third</div>
<br>
<div id="heading"></div>
<br>
<a id="navigator" href="second.html">Next page</a>
Javascript:
(function() {
var currentSelectedDiv;
var heading = document.getElementById('heading');
var navigator = document.getElementById('navigator');
var divs = document.querySelectorAll('.clickable');
for(var i=0; i<divs.length; i++) {
divs[i].onclick = function(e) {
var target = e.target;
currentSelectedDiv = target.getAttribute('id');
heading.innerHTML = ['You have selected ', currentSelectedDiv].join('');
}
}
navigator.onclick = function(e) {
e.preventDefault();
var a = e.target;
var href = a.getAttribute('href');
href += '?previousPageDivId=' + currentSelectedDiv;
alert(href);
//Just uncomment line below
//document.location.href = href;
}
})();
Here you have working example: https://jsfiddle.net/3wdzh2d4/
For a little project I am doing I am interested in creating a small modal form using JavaScripts createElement function. I have the HTML laid out and have actually built the code in JS but sadly cannot seem to get everything to add correctly.
The HTML is supposed to look like this:
<div id="qtModal">
<div id="qtHead">
<span id="qtHeading">Quick Tools</span>
<span id="qtClose">X</span>
</div>
<table id="qtWrapper" border="1">
<tr>
<td id="qtRail">
<ul>
<li><a class="qtLink" href="#">Delete</a></li>
</ul>
</td>
</tr>
</table>
</div>
The JavaScript I set up to make this and append it to the body is as follows:
var qtModal = document.createElement("div");
qtModal.setAttribute("id", "qtModal");
var qtHead = document.createElement("qtHead");
qtHead.setAttribute("id", "qtHead");
var qtHeading = document.createElement("span");
qtHeading.setAttribute("id", "qtHeading");
qtHeading.textContent = "Quick Tools";
var qtClose = document.createElement("span");
qtClose.setAttribute("id", "qtClose");
qtClose.textContent = "X";
var qtWrapper = document.createElement("table");
qtWrapper.setAttribute("id", "qtWrapper");
qtWrapper.setAttribute("border", "1");
var qtTr = document.createElement("tr");
var qtRail = document.createElement("td");
qtRail.setAttribute("id", "qtRail");
var qtUl = document.createElement("ul");
var qtLi1 = document.createElement("li");
var qtA1 = document.createElement("a");
qtA1.setAttribute("class", "qtLink");
qtA1.setAttribute("href", "#");
//We want to build the modal head right here
qtHead = qtHead.appendChild(qtHeading);
qtHead = qtHead.appendChild(qtClose);
qtModal = qtModal.appendChild(qtHead); //Add to modal
//Build the table from the inner most element up to the top
qtLi1 = qtLi1.appendChild(qtA1);
qtUl = qtUl.appendChild(qtLi1);
qtRail = qtRail.appendChild(qtUl);
qtTr = qtTr.appendChild(qtUl);
qtWrapper = qtWrapper.appendChild(qtTr);
qtModal = qtModal.appendChild(qtWrapper); //Add to modal
$("body").append(qtModal); //Add to body
My logic is the we first want to add the heading and the close button to the head element by appending them one at a time. I will then append the head to the actual modal element. Next up I will start building the table from the innermost element (a) up to the outermost element (form) then append those to the Modal. When I use the code above only the innermost element (a) gets appended to the body. I would appreciate it if someone could help either point out what I am doing wrong (I might be misusing createElement or appendChild) or how I could fix it to generate the proper HTML structure listed above.
This is basically fine - the issue is that you're overwriting your existing nodes with your appended nodes. Here's why that's happening.
The appendChild(...) method returns the DOM element that was just appended. So, when you call qtHead = qtHead.appendChild(qtHeading), then
qtHeading gets appended to qtHead
qtHead.appendChild(qtHeading) returns a reference to qtHeading
qtHead gets overwritten with qtHeading
So, to fix this, just take this:
qtHead = qtHead.appendChild(qtHeading);
qtHead = qtHead.appendChild(qtClose);
qtModal = qtModal.appendChild(qtHead); //Add to modal
//Build the table from the inner most element up to the top
qtLi1 = qtLi1.appendChild(qtA1);
qtUl = qtUl.appendChild(qtLi1);
qtRail = qtRail.appendChild(qtUl);
qtTr = qtTr.appendChild(qtUl);
qtWrapper = qtWrapper.appendChild(qtTr);
qtModal = qtModal.appendChild(qtWrapper); //Add to modal
and rewrite it as this:
qtHead.appendChild(qtHeading);
qtHead.appendChild(qtClose);
qtModal.appendChild(qtHead); //Add to modal
//Build the table from the inner most element up to the top
qtLi1.appendChild(qtA1);
qtUl.appendChild(qtLi1);
qtRail.appendChild(qtUl);
qtTr.appendChild(qtUl);
qtWrapper.appendChild(qtTr);
qtModal.appendChild(qtWrapper); //Add to modal