Remove and replace another onclick function in a div through Pure Javascript? - javascript

I have this below span div and I copy this to another place in the DOM. But the onclick function I need to remove and place another onclick function.
<span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>
Here I have to remove the onclick="expand_collapseChildnodes('childNode1')" for the copied element and replace it with onclick="checkNodes('childNode1')"

Consider a sample HTML page:
<html>
<head>
</head>
<body>
<div id ="d1">
<span class="plus childNode1" onclick="expand_collapseChildnodes('childNode1')" id="abc"></span>
</div>
<div id ="d2">
</div>
</body>
</html>
Now to move the element with id abc from DOM element with id d1 to another with id d2
//get the element
var element = document.getElementById("abc");
//detach from source
document.getElementById("d1").removeChild(element);
//remove onclick attribute
element.removeAttribute("onclick");
//add the modified attribute
element.setAttribute("onclick", "sampleFunc()");
//attach the element to another source
document.getElementById("d2").appenChild(element);

http://jsfiddle.net/KvnKZ/1/
var div=document.getElementsByTagName("div");
var span=document.getElementById("abc");
var newSpan=span.cloneNode(true);
newSpan.setAttribute("id","newID"); //change id
newSpan.setAttribute("onclick","myFunc()"); //change onclick event handler
div[0].appendChild(newSpan);

document.getElementById("abc").onclick = function (){checkNodes('childNode1');}

Related

Javascript Function to Click Element that is Defined with Multiple Classes

I am trying to click a button but the only thing that defines it is multiple classes. The element I want to click is
<div class="U26fgb XHsn7e obPDgb M9Bg4d">This is a button </div>
How would I go about clicking it using Javascript?
As long as it is the only <div> element with that class combination, you'd use .querySelector(), which accepts any valid CSS selector as an argument so you can select elements in JavaScript the same way you would in CSS:
// Scan the document for the <div> that has the required classes
let theDiv = document.querySelector("div.U26fgb.XHsn7e.obPDgb.M9Bg4d");
// Set up a click event handling function
theDiv.addEventListener("click", function(){
console.log("you clicked me");
});
// Trigger the click event of the <div>
theDiv.click();
<div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>
FYI: You should get out of the habit of putting spaces on the insides of the < and > delimiters in HTML. Use this:
<div class="U26fgb XHsn7e obPDgb M9Bg4d">Click Me</div>
Not this:
< div class="U26fgb XHsn7e obPDgb M9Bg4d" >Click Me< /div >
very simple with jQuery:
$(".U26fgb.XHsn7e.obPDgb.M9Bg4d").click(function(){
console.log("clicked!");
});
const div = document.querySelector('div .M9Bg4d');
div.addEventListener("click", ()=> {
// here put what you wanna do after clicking the div.
});
onclick attribute works well inside almost all the html tags and here is the simple solution to click on the div and get a result. All the Best!
function clickDiv(){
console.log("Div is Clicked");
}
<div class="U26fgb XHsn7e obPDgb M9Bg4d" onclick="clickDiv()">This is a button </div>

can I remove a line in my HTML code with javascript?

I have this code:
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>
and I want to make a javascript code to remove the div below the input field whenever I write anything in the input
..........
I tried this code:
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
var parent = field.parentNode;
parent.innerHTML = field.outerHTML;
field.value = num;
}
but it have a problem each time I make an input, I have to re-click inside the input to make it active again
check out the code here
You should not use inline HTML event attributes to wire up event handlers. That technique is 25+ years old and will not die the death it deserves because people just keep copying it from other code they've seen.
See the comments for the simple explanation:
// Add the event handler to the input in JavaScript, not in HTML
document.getElementById("myID").addEventListener("input", removeElement);
function removeElement(){
// Remove the sibling element that follows the input
document.querySelector("#myID").nextElementSibling.remove();
// Now that the element has been removed, this function is no
// longer required, so remove the event handler to prevent attempts
// to remove it again when it's no longer there. "this" refers to
// the object that caused this function to be invoked (the input
// element in this case).
this.removeEventListener("input", removeElement);
}
<div class="input">
<input type="number" id="myID">
<div>
<h3>MY TEXT</h3>
</div>
</div>
How to remove an HTML element using JavaScript ?
Given an HTML element and the task is to remove the HTML element from the document using JavaScript.
Approach:
Select the HTML element which need to remove.
Use JavaScript remove() and removeChild() method to remove the
element from the HTML document.
Exemple to remove a div :
div.parentNode.removeChild(div);
Follow this link for more information.
I hope I was able to help you.
<div class="input">
<input type="number" id="myID" >
<div id="id2">
<h3>MY TEXT</h3>
</div>
</div>
<script>
document.getElementById("myID").oninput = function() {myFunction()};
function myFunction() {
document.getElementById("id2").innerHTML="";
}
</script>
Problem with using innerHTML is you are basically using a whiteboard. You erase everything on it and you have to redraw it all. That means you would need to reset the value and focus. It is doable, just not practical.
The better thing to do would be to select the element and remove it with .remove()
var field = document.getElementById("myID");
var num = field.value;
if (num.length) {
field.nextElementSibling.remove()
}
It will work, but you will be better off using a class to hide the element. It also has the benefit that if the user deletes the text in the input, you can reshow the message. I would just hide it with a css class with toggle. I would select the div with nextElementSibling.
function myFunction(){
var field = document.getElementById("myID");
var num = field.value;
field.nextElementSibling.classList.toggle('hidden', num.length)
}
.hidden {
display: none;
}
<div class="input">
<input type="number" id="myID" oninput="myFunction()">
<div>
<h3>MY TEXT</h3>
</div>
</div>

JavaScript changing values of element having the same ID dilemma

So basically what I'm currently facing is kind of embarrassing, I've created a function which dynamically creates new elements and add it to the DOM. The function is replicating the elements( the same id) whenever the triggered button is being clicked. I have a range slider which when i slide should change a the p tag, the problem now is that since the p tag has been replicated with the function(all p tag has the same id) only the first p tag is being changed. I would like to know what can I do in order to solve this problem. Any help?
//this function creates elements, it contains the range and //the p tag which needs to p change
function createElements(){
var divelement = $('<input class ="timer" type="range" min="3" max="20" value="10"oninput="showValue(this.value)"></input><p id="changeP"></p>');
$('#userQuestions').append(divelement);
}
function showValue(value){
this.document.getElementById("changeP").innerHTML=value+" Minutes";
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>
</body>
</html>
Run the snippet to see the problem thanks.
Remove the duplicate ids and simply select the next sibling, and populate its textContent:
const userQuestions = document.querySelector('#userQuestions');
function createElements() {
userQuestions.insertAdjacentHTML(
'beforeend', '<input class ="timer" type="range" min="3" max="20" value="10"oninput="showValue(this)"><p></p>'
);
}
function showValue({ nextElementSibling, value }) {
nextElementSibling.textContent = value;
}
<div id="userQuestions"></div>
<button type="button" onclick="createElements()">add elements</button>

change display of element with class x by clicking element with class y (JS)

Using JS or Jquery (preferred JS) how can I change the display style of an element after clicking on another element (both elements identified by their respective classes).
The below doesnt seem to work.
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<i id="xyz" class="class1" >hey</i>
<div id="abc" class="class2" style="display: block;">lo</div>
<script type="text/javascript>
$(function() {
$(".xyz").click(function() {
console.log("element with class xyz was clicked");
$(".abc").css('display': 'none');
});
});
</script>
the console doesnt even log anything
It looks like you are trying to reference your IDs by using CLASS syntax in your jQuery selector.
Instead of using $(".xyz") use $("#xyz"). Same for your $(".abc") selector.
Hope that helps!
You should use document.querySelector(cssSelector) for getting elements by class or id or document.getElementById to get elements by id only.
Here is VanilaJS solution:
var firstElem = document.querySelector(".class1");
firstElem.addEventListener("click", function(event){
var secondElem = document.querySelector(".class2");
secondElem.style.display = "none";
})
<i id="xyz" class="class1" >hey</i>
<div id="abc" class="class2">lo</div>

Changing HTML div's background colour when it is clicked using JavaScript without jQuery

Trying to implement a very simple feature, using only JavaScript without jQuery. I want the background of the HTML div with id='tags' to change, when I click on it.
document.getElementById('tags').addEventListener('onclick', function() {
this.style.backgroundColor = 'red';
});
<body>
<div id="tags">Item1</div>
<div id='tags'>Item2</div>
<div id='tags'>Item3</div>
</body>
Identiifiers in HTML must be unique, Use a common CSS class to instead.
Use querySelectorAll() to target them, as it will return a list, iterate it and bind event handlers
remove prefixed "on"
document.querySelectorAll('.tags').forEach(function(element) {
element.addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
})
<div class="tags">Item1</div>
<div class='tags'>Item2</div>
<div class='tags'>Item3</div>
A few issues here:
your script is (or was before you edited the question) executing before the <div> elements are added to the document; the <script> needs to be placed after the <div>s in your HTML source code.
you can't have multiple elements with the same id. use class="tags" instead.
the event is "click" not "onclick"
Here's what i'd do instead:
<body>
<div class="tags">Item1</div>
<div class="tags">Item2</div>
<div class="tags">Item3</div>
<script>
for (let x of document.getElementsByClassName('tags')) {
x.addEventListener('click', function() {
this.style.backgroundColor = 'red';
});
}
</script>
</body>

Categories