Point out the current DOM class being used in JS? - javascript

I am struck in a problem, where I need to point out the current number of the class I am using in JS. For example here is my code:
<div>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction()">Click here</button></p>
</div>
Now I know if I type document.getElementsByClassName("child"), it will provide me an array with all the able usage of class p mentioned. However I want to know the exact button which was clicked.
Like if the second button p class was clicked, I want my function to return me the number 2. Similarly if the third button was clicked, I want the number 3 returned to me. Is there any function for that? How should I proceed? I am completely new to JS.

What you're trying to do is called Event Delegation in javascript. You just add the event listener on the parent element in order to avoid having to add event handlers to multiple child elements.
e.target gives you the element on which the event handler (here click) was called on. You can get info regarding that element using various properties like e.target.textContent gives you the button text.
const container = document.querySelector(".container")
container.addEventListener('click',(e)=>{
console.log(e.target)
console.log(e.target.textContent)
})
<div class="container">
<p><button type="button">Click here 1</button></p>
<p><button type="button">Click here 2</button></p>
<p><button type="button">Click here 3</button></p>
<p><button type="button">Click here 4</button></p>
</div>

You can pass this to the function, which is the current element.
I've added code to find all .child elements, and find the index that matches this button's parent, and then alert it.
I would recommend using addEventListener instead of onclick attributes.
Depending on what you are doing, I'd recommend adding data="n" attributes added to the DOM elements, or an object map of values. But this will work as is:
function myfunction(el){
const index = Array.from(document.getElementsByClassName('child'))
.findIndex(x=>x===el.parentNode);
alert(index);
}
<div>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
<p class="child"><button type="submit" onclick="myfunction(this)">Click here</button></p>
</div>

You can loop over the list of elements having this class, add the event listener to each item, so you can access the number inside the function normally. Here is an example:
let childs = document.getElementsByClassName('child');
for(let i = 0; i < childs.length; i++){
let el = childs[i];
el.addEventListener('click', function(e){
console.log(i+1);
});
}
<div>
<p class="child"><button type="submit">Click here 1</button></p>
<p class="child"><button type="submit">Click here 2</button></p>
<p class="child"><button type="submit">Click here 3</button></p>
<p class="child"><button type="submit">Click here 4</button></p>
</div>

Related

Getting the parent of button without ID in Javascript [duplicate]

This question already has answers here:
JS get the clicked element with event.target
(4 answers)
Getting the parent div of element
(7 answers)
Closed 3 years ago.
I am struggling to get the parent of button when it is clicked. This is my HTML structure:
<p><button class="remove">x</button> Hamlet<input value="5"></p>
I don't want to use the ID in button because I have many of the same buttons. Any help is appreciated. Thanks!!!
Like this? Note I delegate from a container
document.getElementById("container").addEventListener("click", function(e) {
let tgt = e.target;
if (tgt.classList.contains("remove")) tgt.closest("p").remove();
})
<div id="container">
<p><button class="remove">x</button> Hamlet<input value="1"></p>
<p><button class="remove">x</button> Ophelia<input value="2"></p>
<p><button class="remove">x</button> Polonius<input value="3"></p>
</div>
For browser that doe not like closest you can use tgt.parentElement.remove()
Maybe consider adding a universal click event to all buttons.
const onClickButton = function () {
// The parent element
const parent = this.parentElement;
parent.style.backgroundColor = 'red';
};
[...document.getElementsByTagName('button')].forEach(button => button.addEventListener('click', onClickButton));
<p>
<button class="remove">x</button>
Hamlet1
<input value="5">
</p>
<p>
<button class="remove">x</button>
Hamlet2
<input value="5">
</p>
<p>
<button class="remove">x</button>
Hamlet3
<input value="5">
</p>

how to add button value from tag a title on load

I'm working on my real-estate project, I have a contact modal box and I want to get the title from tag a into the button value in modal box.
I'm not good at English, if I'm saying something wrong somewhere please forgive me
I have tried many ways but it still doesn't work and the result I get is the title but only works just for 1 id
function change() {
let a_id = document.getElementById('test');
let btn_id = document.getElementById("btn-test");
let btn = a_id.getAttributeNode('title').value;
// btn_id.value = btn;
btn_id.innerHTML = btn_id.value = btn;
}
<body>
<p>Click the button find out if the button has an onclick attribute specified.</p>
hello
<input type="button" onload="change()" title="hello" value="Try it" id="btn-test">
</body>
this is my code https://hastebin.com/ohasiqavun.xml?
You are supposed to use classes instead of ids here. Ids are unique and thus it only works for 1 element.
I just created the following alternative for you to get the values from every button seperate. noticed that I changed the HTML to 3 container who all include the same content. I removed the ID's and changed them for classes:
JS:
let changeallbuttons = document.querySelector('.changeallbuttons')
changeallbuttons.addEventListener('click', function() {
document.querySelectorAll('.container').forEach(item =>{
let button = item.querySelector('input')
let a = item.querySelector('.test')
button.value = a.getAttribute('title')
})
})
document.querySelectorAll('.container').forEach(item =>{
item.addEventListener('click', function() {
let button = item.querySelector('input')
let a = item.querySelector('.test')
button.value = a.getAttribute('title')
})
})
HTML:
<div class="container">
<p>Click the button find out if the button has an onclick attribute specified.</p>
<a href="#" title="bye1" class="test" >hello</a>
<input type="button" title="hello" value="Try it">
</div>
<div class="container">
<p>Click the button find out if the button has an onclick attribute specified.</p>
<a href="#" title="bye2" class="test" >hello</a>
<input type="button" title="hello" value="Try it">
</div>
<div class="container">
<p>Click the button find out if the button has an onclick attribute specified.</p>
hello
<input type="button" title="hello" value="Try it">
</div>
<input class="changeallbuttons" type="button" title="hello" value="Try it">

How to get text for div close to button clicked

I'm trying to get the text of some div within the parent div where button is clicked. This is an example code
<div class="parentDiv" >
<div id="divToFind" style="display:none">text</div>
<div class="btn-group">
<button class="button" type="button" >Remove</button>
</div>
</div>
<div class="parentDiv" >
<div id="divToFind" style="display:none">text2</div>
<div class="btn-group">
<button class="button" type="button">Remove</button>
</div>
</div>
Here parentDiv is repeated couple of times and text of divToFind is different in each parentDiv. Whenever remove button is clicked within the parentDiv I want to get the text of divToFind.
I have tried this
$(this).closest('.parentDiv').children('#divToFind').text();
But nothing is returned
Don't use same IDs in a single document. You should use classes instead. With class, it works fine.
It is mentioned in the spec that there must not be multiple elements in a document that have the same id value.
$(function(){
$("button").on("click", function(){
var t = $(this).closest('.parentDiv').children('.divToFind').text();
console.log(t);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parentDiv" >
<div class="divToFind" style="display:none">text</div>
<div class="btn-group">
<button class="button" type="button" >Remove</button>
</div>
</div>
<div class="parentDiv" >
<div class="divToFind" style="display:none">text2</div>
<div class="btn-group">
<button class="button" type="button">Remove</button>
</div>
</div>
Yes, Its true, you should not use same Id for 2 elements in an HTML document, However following is the code that can help you to get the text of the div given.
There are 2 ways:
$(this).parent().prev('#divToFind').text();
$(this).parent().prev().text();
prev and next allows us to traverse on the same level. You can provide selectors inside that to get particular element.
In your example its ID, you can update Id to some css class, so that you dont have to have elments with same ID.

filling a text-field with click-event-information

HTML
<div id="wrapper">
<input type="text" id="text">
<button id="t-1" value="1">1</button>
<button id="t-2" value="2">2</button>
<button id="t-3" value="3">3</button>
</div>
JavaScript
$(function() {
$('#wrapper').click(function(event) {
$('#text').append(event.target.value);
});
});
Clicking the button does not change the text-field-value!
Use this:
$(document).ready(function(){
$('#wrapper').click(function(event) {
$('#text').val(event.target.value);
});
});
Remember append is to add HTML content, whereas val is to get and set the input field value.
append adds HTML content after the input. What you are looking for (changing the text of the input) is val.
You need to use val() to set value of a textbox. append() is used to append a DOM element into another element (like appending dynamic li into ul tags). Below is a working snippet
$(function() {
$('#wrapper').click(function(event) {
$('#text').val(event.target.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<input type="text" id="text">
<button id="t-1" value="1">1</button>
<button id="t-2" value="2">2</button>
<button id="t-3" value="3">3</button>
</div>

How hide div if another div is open use javascript

i have div like this use javascript :
<script>
$(document).ready(function(){
$("#btnmsg-1").click(function(){
$(".msgid-1").show();
});
$("#btnmsg-2").click(function(){
$(".msgid-2").show();
});
$("#btnmsg-3").click(function(){
$(".msgid-3").show();
});
$("#btnmsg-4").click(function(){
$(".msgid-4").show();
});
});
</script>
<div>NAME : ABCDEF <button id="btnmsg-1">message</button></div>
<div class="msgid-1" style="display:none;"><textarea></textarea><input type="submit" name="btnsend" value="Send"></div>
<div>NAME : GHIJKL <button id="btnmsg-2">message</button></div>
<div class="msgid-2" style="display:none;"><textarea></textarea><input type="submit" name="btnsend" value="Send"></div>
<div>NAME : MNOPQR <button id="btnmsg-3">message</button></div>
<div class="msgid-3" style="display:none;"><textarea></textarea><input type="submit" name="btnsend" value="Send"></div>
<div>NAME : STUVWX <button id="btnmsg-4">message</button></div>
<div class="msgid-4" style="display:none;"><textarea></textarea><input type="submit" name="btnsend" value="Send"></div>
if i click button id="btnmsg-1" then div class="msgid-1" show, and then i click button id="btnmsg-3" then div class="msgid-3" show but div class="msgid-1" not hide or close,my question how hide the div if another div is open?
Instead of using separate handlers for each, you can use the related positioning of the elements along with classes to group them to show/hide
ie, Add a class like btnmsg to all the buttons and msgedit to all the div's that have to be shown/hidden. Now register a click handler to .btnmsg elements, from your markup the .msgedit element to be shown is the next sibling of the clicked button so show that then hide all other .msgedit elements.
$(document).ready(function() {
var $edits = $('.msgedit')
$(".btnmsg").click(function() {
var $this = $(this).parent().next().show();
$edits.not($this).hide()
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>NAME : ABCDEF
<button class="btnmsg" id="btnmsg-1">message</button>
</div>
<div class="msgid-1 msgedit" style="display:none;">
<textarea></textarea>
<input type="submit" name="btnsend" value="Send" />
</div>
<div>NAME : GHIJKL
<button class="btnmsg" id="btnmsg-2">message</button>
</div>
<div class="msgid-2 msgedit" style="display:none;">
<textarea></textarea>
<input type="submit" name="btnsend" value="Send" />
</div>
<div>NAME : MNOPQR
<button class="btnmsg" id="btnmsg-3">message</button>
</div>
<div class="msgid-3 msgedit" style="display:none;">
<textarea></textarea>
<input type="submit" name="btnsend" value="Send" />
</div>
<div>NAME : STUVWX
<button class="btnmsg" id="btnmsg-4">message</button>
</div>
<div class="msgid-4 msgedit" style="display:none;">
<textarea></textarea>
<input type="submit" name="btnsend" value="Send" />
</div>
Please add same classes to similar elements, and then use this jQuery code instead:
$(document).ready(function(){
$(".btnmsg").click(function(){
$(".msgid").hide();
$(this).parent().next(".msgid").show();
});
});
See the complete DEMO working: https://jsfiddle.net/lmgonzalves/n5f78kqs/
jsBin demo
don't use msgid-1, msgid-2 etc... cause it defeats the purpose of classNames. Use only msg
Same goes for your buttons. Remove the buttons IDs. use Class class="btn"
Don't use inline styles. Use <style> instead or call-to an external stylesheet.
HTML
<div class="btn">
NAME : ABCDEF <button>message</button>
</div>
<div class="msg">
<textarea></textarea>
<input type="submit" name="btnsend" value="Send">
</div>
CSS:
.msg{
display:none;
}
See how more readable is now your code?
jQuery:
var $msg = $(".msg"); // Get all .msg DIVs
$(".btn").on("click", "button", function( e ){
$msg.hide(); // Hide all
$(e.delegateTarget).next().show(); // Show next
});
You can do this by calling hide() on the elements you would like to hide.
For example, you would make the following change:
// Old
$("#btnmsg-1").click(function(){
$(".msgid-1").show();
});
//New
$("#btnmsg-1").click(function(){
$(".msgid-1").show();
$(".msgid-2").hide();
$(".msgid-3").hide();
$(".msgid-4").hide();
});
A cleaner way to do this would be to give all of your messages a "message" class, then your onClick handlers would look like this:
$("#btnmsg-1").click(function(){
$("#message").hide();
$(".msgid-1").show();
});
Hope that helps!

Categories

Resources