How to delete HTML section using a function of js? - javascript

I need to remove a HTML section using a button. The button is in the HTML section I want to remove. And the section I want to remove was previously added by a button.
With Add section button I add a section below the first section, but I can't create a function to remove a section, I can't select the section I want to remove.
image of web

You're able to use the remove() method in order to do that.
Example:
HTML:
<div id="testID">your stuff.</div>
<button onclick="deleteDiv()">Delete</button>
JS:
function deleteDiv() {
var selectedDiv = document.getElementById("testID");
selectedDiv.remove();
}

try this code:-
<p id ="remove" style = "color: green; font-size: 24px; font-weight: bold;">
on click remove this section
</p>
<button onClick = "remove()">
click here
</button>
var htmlElement = document.getElementById('remove'); //use getElemeyId or getElementsByClassName According to your need;
function remove() {
htmlElement.remove();
}

Related

Creating a script for a button to close other sections when opening its own sections

This is hard to explain precisely. But here we go:
I have a button that calls a function
<button onclick="myFunction_gsm()">Men</button>
When the button is pressed, it triggers a script. This script grabs a hidden section and displays it. The script goes like this:
<script>
//Gender Selection Script Men//
function myFunction_gsm() {
var x = document.getElementById("men-sizing");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
</script>
On the screen this plays out so that you click the button, a section appears, if I click the same button again the section hides again. However, I have another 2 sections. 3 Sections in total. For this example, the above script works for 1 section, the A section. There is also B and C. I would like to include the behavior that when A has been pressed, therefore displaying section A, if I then press the button for B the B section appears but the A section disappears without having to press the A button again. A Dynamic change of sorts.
I am a complete starter for coding but I assume it's something you add into the if statement. Any help would be greatly appreciated.
I would prefer solutions that incorporate the code I have now, since I won't have much use recreating it from scratch. It would solve this, but cause many new problems.
Define a class for all sections, for example sec. On click event pass the selected id, hide all of them and just toggle the selected one.
function myFunction_gsm(sectionId) {
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
if(itm.id !== sectionId) itm.style.display = 'none'
})
var x = document.getElementById(sectionId);
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
let sec = document.querySelectorAll('.sec');
sec.forEach(itm => {
itm.style.display = 'none'
})
<button onclick="myFunction_gsm('sec1')">Sec1</button>
<button onclick="myFunction_gsm('sec2')">Sec2</button>
<button onclick="myFunction_gsm('sec3')">Sec3</button>
<div class="sec" id="sec1"> some text 1 here</div>
<div class="sec" id="sec2"> some text 2 here</div>
<div class="sec" id="sec3"> some text 3 here</div>
You might use class names for the sections. Then at the start of the function have all elements with that class name be hidden and afterwards display the currently clicked one.
If you want to preserve the toggle functionality for the section (so clicking A twice displays and hides it again), you want to check the display state of the currently clicked one first before hiding all. And then only display the clicked one if it was hidden before.
The modern approach is to avoid using .style within JS. This add the stylign as inline-style which ahs the highest specificty weight with exeption of important. The modern solution is to use classList to apply, remove or toggle a CSS-Class.
You add a class to CSS to hide element such as: .display-none { display: none; }`
Then you add a function to your button to hide all sections with a certain class by adding the class mentioned at step 1: function hideAll() { document.querySelectorAll('.class-name').forEach(el => el.classList.add('display-none')); }
You add a second function to the onclick trigger of a button thow a certain element by removing the class: element.classList.remove('display-none');
function hideAll() {
document.querySelectorAll('.section').forEach(el => el.classList.add('display-none'));
}
function showA() {
document.querySelector('#section-a').classList.remove('display-none');
}
function showB() {
document.querySelector('#section-b').classList.remove('display-none');
}
function showC() {
document.querySelector('#section-c').classList.remove('display-none');
}
.display-none {
display: none;
}
<button onclick="hideAll(); showA()">Show A</button>
<button onclick="hideAll(); showB()">Show B</button>
<button onclick="hideAll(); showC()">Show C</button>
<section id="section-a" class="section display-none">Section A</section>
<section id="section-b" class="section display-none">Section B</section>
<section id="section-c" class="section display-none">Section C</section>
CSS-only Solution
If you dont want to sue scripts, you could use a pure CSS-Method that works through the :target selector. This allows you to use anchor as "trigger".
Hide the scetiond with display: none; either by selecting them directly or adding a class to them.
use an anchor with an href="#id" instead of a link. This will move the page to that element but also manipulate the websites adress.
Use *:target { display: block; } to show targeted elements:
.display-none {
display: none;
}
*:target {
display: block;
}
/* for styling purpose only */
a {
margin-right: 15px;
}
Show A
Show B
Show C
<section id="section-a" class="display-none">Section A</section>
<section id="section-b" class="display-none">Section B</section>
<section id="section-c" class="display-none">Section C</section>

HTML DOM getElementsByTagName issue

Currently, both this is using a button, but is there a possible to have this query without a button but just onclick?
Changes the target of the anchor to google.com:
<button onclick="document.querySelectorAll('ul>li>a').forEach(function(link){link.href='http://google.de';});"> ChangeHREF </button>
Changes the color of the header of the page:
<button onclick='(document.getElementsByTagName("h1")[0]).style.color="blue"'>XSS attach</button>
Add an eventlister for click on a tag e.g. a DIV that starts a function (change). In this function get with querySelector your header H1 and a class blue. Via CSS the color of the header changes to blue.
So you don't need a button for this.
document.getElementById('myDiv').addEventListener('click', change);
function change() {
document.querySelector('h1').classList.add("blue");
}
h1.blue {
background: blue;
}
<h1>Header</h1>
<div id="myDiv">Press this DIV for change H1 to blue</div>
of course you can here is one I used div and you can use other but in the way makes sense like you can't use select
change.onclick = () => {
document.getElementsByTagName('h1')[0].style.color = 'red';
}
<h1>Hello world</h1>
<div id="change">Change Color</div>
change.onclick = () => {
document.querySelectorAll('a').forEach(link => {
link.href = 'http://google.de';
});
var links = document.getElementsByTagName('a');
console.log(links[0].href);
console.log(links[1].href);
}
a
b
<div id="change">Change</div>

I can't add or remove a class

I am trying to remove a class and add a class within one function. But when I click on the button nothing is happening.
This is my code
function unlikeVerhaal(unlike) {
unlike.preventDefault;
document.querySelector('#unliked').classList.add('onzichtbaar');
document.querySelector('#liked').classList.remove('onzichtbaar');
}
document.querySelector('.likebutton').addEventListener('submit', unlikeVerhaal);
.onzichtbaar {
display: none;
}
<li>
<button type="submit" class="likebutton">
<img src="icons/lined.png" alt="lined heart" class="unliked" id="unliked">
<img src="icons/solid.png" alt="solid heart" id="liked" class="onzichtbaar">
</button> 777
</li>
What I am trying to get is that the class is added to the first image and removed by the second image.
You just need to use a combination of the three methods .contains(), .add() and .remove() from the element.classList property along with a simple if/else statement (or a ternary operator if you prefer that) as can be seen in the Code Snippet below:
var btn = document.querySelector('.likebutton');
function unlikeVerhaal() {
var ul = document.getElementById("unliked");
var l = document.getElementById("liked");
if (ul.classList.contains("onzichtbaar")) {
ul.classList.remove("onzichtbaar");
l.classList.add("onzichtbaar");
console.log("Inspect your elements to see the class switching!")
} else {
l.classList.remove("onzichtbaar");
ul.classList.add("onzichtbaar");
console.log("Inspect your elements to see the class switching!")
}
}
btn.addEventListener("click", unlikeVerhaal)
.onzichtbaar {background-color: green;}
<li>
<button type="button" class="likebutton">
<div class="unliked" id="unliked">A</div>
<div id="liked" class="onzichtbaar">B</div>
</button> 777
</li>
You can either inspect the elements to see the class switching between the two or you can just watch the green background styling which is applied to an element with the onzichtbaar class name switching between the two.
This will works as you expect:
function unlikeVerhaal(e) {
e.preventDefault;
document.getElementById('unliked').classList.add('onzichtbaar');
document.getElementById('liked').classList.remove('onzichtbaar');
}
document.getElementById('likebutton').addEventListener('click', unlikeVerhaal);
Just change submit to click and remove type from button
Fiddle
Update:
Updated fiddle

Display elements in order of click

How can I have elements .show in the order they're clicked and not the order they're appear in the HTML using jquery?
E.g.
Css code:
.sq{
display:none;
}
Html Code:
A
B
C
<span class="sq" id="01">a</span>
<span class="sq" id="02">b</span>
<span class="sq" id="03">c</span>
JavaScript code:
$("#1").click(function(){
$("#01").show();
});
$("#2").click(function(){
$("#02").show();
});
$("#3").click(function(){
$("#03").show();
});
Using this code if I click C,B,A the output will arrange "a b c"
What I would like is if I click C,B,A the output should arrange "c b a"
I've tried various CSS positioning rules to do this, but the best I can do is have them arrange in the same position as each other. I realize I could make a new class for each but would rather not do it that way in the interest of minimal code and I'm learning right now so it would be useful to know a better way around the issue.
Here's a fiddle: http://jsfiddle.net/xuxsuagg/4/
You can do something like
$(".myclass").one('click', function() {
$($(this).data('target')).appendTo('.output').show();
});
a {
text-decoration: none;
}
.sq {
display: none;
}
.output {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
A
B
C
D
E
F
<p class="output">
<span class="sq" id="01">A</span>
<span class="sq" id="02">B</span>
<span class="sq" id="03">C</span>
<span class="sq" id="04">D</span>
<span class="sq" id="05">E</span>
<span class="sq" id="06">F</span>
</p>
Notes
Used a common event handler instead of using different handlers for each link
Before shown the element the target is moved to the last position of the parent
Used .one() to register the handler so that one element is shown only once
There is a very simple trick: use .append(). When you append a selected element that is already present in the DOM, you are actually moving it around. Also, I recommend that to optimize your code, you can:
Use a common class for the <a> elements
Assigned a HTML5 data- attribute, say data-target, to specify the ID of its intended target
Listen to click events triggered on the common class
An example of the proposed new markup:
A
B
<!-- and more -->
Here is the code (and the demo fiddle here—http://jsfiddle.net/teddyrised/xuxsuagg/9/)
$('.sq-click').click(function(e) {
// Prevent default action
e.preventDefault();
// Use .append() to move element
var $out = $('.output');
$out.find('#'+$(this).attr('data-target')).appendTo($out).show();
});
On a side note, if you do not want the users to rearrange the order after an anchor has been clicked, you will have to rely on the .one() method for listening to click events. Also, it will help that you style the disabled anchors appropriately so the users can see it—see proof-of-concept demo: http://jsfiddle.net/teddyrised/xuxsuagg/26/
$('.sq-click').one('click', function(e) {
// Prevent default action
e.preventDefault();
// Use .append() to move element
var $out = $('.output');
$out.find('#'+$(this).attr('data-target')).appendTo($out).show();
// Add class to change appearance of disabled <a>
$(this).addClass('disabled');
});
And your CSS can look like this:
.disabled {
cursor: default;
opacity: 0.2;
}
You can simplify this code to:
var a = document.getElementsByTagName('a');
for (i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var span = document.createElement('span');
var text = document.createTextNode(this.innerHTML + " ");
span.appendChild(text);
document.getElementsByClassName('output')[0].appendChild(span);
})
}
a {
text-decoration: none;
}
.sq {
display: none;
}
A
B
C
D
E
F
<p class="output">
</p>
Bind the click event to the class that they share and not their own unique id.
In the function scope of clickClosure 'this' is referring to the current element.
$(".sq").click(function clickClosure(){
$(this).show();
});
Using styles to achieve this might range from painful to very hard, depending on the exact way you want them displayed. I'd suggest instead to re-order them in DOM. That might look something like this:
<a id="link-1">...</a>
...
<div style="display: none" id="hidden-items">
<span id="item-1">...</span>
</div>
<div id="visible-items"></div>
&
$('#link-1').click(function () {
$('#visible-items').append($('#item-1'));
});
As other respondents suggested, you could also optimize your code in various ways, but that's outside the scope of the question.
Try this: You can put empty <p class="output"> and remove display:none; from CSS .sq{... In jQuery, create a <span> on the basis of clicked link and append it to <p class="output">
HTML:
A
B
C
D
E
F
<p class="output">
</p>
CSS:
.sq{
/*display:none;*/
color: green;
margin-right: 10px;
}
jQuery
$("a[href='#']").click(function(e){
e.preventDefault();
var text = '<span class="sq" id="0'+$(this).prop('id')+'">'
+$(this).text()+'</span>';
$(text).appendTo('p.output');
});
DEMO

How to bold label on click?

So the labels are populated from the database. Once the label is clicked, the label need to turn red and bold. when clicked on another label, the first label need to come back to original state and the new label should be activated and it needs to be bold and red. for some reason, the changeActiveStates() only works for the first 2 labels, i.e., when first label is clicked it turns red and when the second label is clicked the first label is turned black and the second label is turned red. when the third label is clicked, the second label remains red and the third one turns red. How do i fix this??
Here is the code:
<html>
<span>
<input type="hidden" name="LiabFilter" id= "idLib<%=liabkey %>" value="<%=liabkey %>" />
<div>
<label for="idLib<%=liabkey%>" id="liablabel" style="cursor: hand; padding-left: 25px; font-weight: normal"
onClick ="clearLiabFilter();
document.getElementById('idLib<%=liabkey%>').checked = true;
changeActiveStates(this);">
<%=liab.getName() %>
</br>
</label>
</div>
</span>
<style type="text/css">
.activate { font-weight: bold; color:#e40000;}
.visited{ font-weight: normal; color: #000000;}
</style>
<script>
function byId(id) {
return document.getElementById ? document.getElementById(id) : document.all[id];
}
var prevLink = "";
function changeActiveStates(ele) {
if (prevLink) byId(prevLink).className = '';
ele.className = 'activate';
prevLink = ele.id;
}
</script>
</html>
Are you averse to JQuery?
If not, this should work.
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
EDIT: Example on jsFiddle
EDIT: A little more detail as the questioner hasn't used JQuery before.
JQuery is a javscript library and so must be loaded by the browser before you can do all the nifty stuff.
Add the following between the <head></head> tags on your page:
<script src="http//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
(Why let google host JQuery for you?)
Then add the following, also between the tags but after the script tag given above:
$(document).ready(function() {
$('label').click(function() {
$('label').removeClass('activate'); /* Remove 'activate' class from all labels */
$(this).addClass('activate'); /* Add 'activate' class to clicked label
});
});
(What does $(document).ready() do?)
Maybe not the best of solutions, but have you considered using jQuery? It's generally not too much of a dependency , and will solve these sort of issues quite elegantly and easily for you. Plus. Cross-browser compatibility.

Categories

Resources