How to know the id of current Html element when clicking on a Html element using plain JavaScript?
<div id="myId">
<div>
<h2>First Div</h2>
</div>
<div>
<h2>Second Div</h2>
</div>
</div>
I would like to catch "myId" while I am clicking on the body of this div. That means I would like to get the ID of parent div when I click on First Div and Second Div.
My JS code is like below.
document.onclick = function(e) {
alert(e.target.id)
}
You can do that in the following way:
var div = document.getElementById('myId');
div.addEventListener('click', function(e){
console.log(this.getAttribute('id'))
});
<div id="myId">
<div>
<h2>First Div</h2>
</div>
<div>
<h2>Second Div</h2>
</div>
</div>
event.currentTarget will be the dom element that the event is triggered by.
You can just write a function:
function showid(elem) {
var id = elem.id
console.log(id)
alert(id)
}
And in your HTML code:
<div id="myId" onclick="showid(this)">
<div>
<h2>First Div</h2>
</div>
<div>
<h2>Second Div</h2>
</div>
</div>
You can do it like this in vanilla JS, register an event handler on the document and retrieve the id of the clicked element:
document.addEventListener("click", function(e){
alert(e.srcElement.id);
});
<p id="paragraph1">First Paragraph</p>
<button id="myButton">Click Me</button>
Related
I am having difficulty to get text content of h1 at a time when I click on any button element . Can anyone help me out please?
<div id="makeSelection" ><h1>Text Content 1</h1>
<button onclick="eveent()">Click Me</button>
</div>
<div id="makeSelection" ><h1>Text Content 2</h1>
<button onclick="eveent()">Click Me</button>
</div>
<div id="makeSelection" ><h1>Text Content 3</h1>
<button onclick="eveent()">Click Me</button>
</div>
function eveent(){
var text = document.getElementById('makeSelection').textContent;
console.log(text);
}
I would suggest to make addEventListener in javascript and clear the click event from HTML template..
Then use eveent.bind(this, item.textContent) to bind the particular item which was listened in click event.
Edit:
If you want to add event listener to a button, then get the button like, (Assuming you have class name for each div as makeSelection and not same id's repeated.
const selection = document.querySelectorAll(".makeSelection button");
Then make an event listener like,
item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))
Through item.previousElementSibling.textContent , we are passing the textContent of h1 tag..
const selection = document.querySelectorAll(".makeSelection button");
function eveent(clickedItem){
console.log(clickedItem)
}
selection.forEach((item,i) => {
item.addEventListener('click', eveent.bind(this,item.previousElementSibling.textContent))
})
<div class="makeSelection" >
<h1>Text Content 1</h1>
<button>Click Me</button>
</div>
<div class="makeSelection">
<h1>Text Content 2</h1>
<button>Click Me</button>
</div>
<div class="makeSelection">
<h1>Text Content 3</h1>
<button>Click Me</button>
</div>
This is one way how you could do it:
Give ID-s to the headings.
Call the click event with the id of the desired heading.
Do your thing with the element content. (In this example, you console log it's text content)
function clickEvent (target){
var heading = document.querySelector(target);
if (heading) {
console.log(heading.textContent);
}
};
<div>
<h1 id="heading-1">Text Content 1</h1>
<button onclick="clickEvent('#heading-1')">Click Me</button>
</div>
<div>
<h1 id="heading-2">Text Content 2</h1>
<button onclick="clickEvent('#heading-2')">Click Me</button>
</div>
<div>
<h1 id="heading-3">Text Content 3</h1>
<button onclick="clickEvent('#heading-3')">Click Me</button>
</div>
Note: I removed the duplicate ids from the divs, as they are not required and also duplicate IDs are not valid in HTML.
A simple example with plain Javascript to read the content of clicked div
<html>
<head>
<script>
function eveent(c) {
alert(c.childNodes[0].innerText);
}
</script>
</head>
<body>
<div class="makeSelection" onclick="eveent(this)"><h1>Text Content 1</h1></div>
<div class="makeSelection" onclick="eveent(this)"><h1>Text Content 2</h1></div>
<div class="makeSelection" onclick="eveent(this)"><h1>Text Content 3</h1></div>
</body>
</html>
try to get the h1 inside "makeSelection" and make button outs
<div id="makeSelection"><h1>Text Content 1
</h1>
function eveent(){
var text = document.querySelector("#makeSelection h1").innerText
}
I want to get the rowIndex of the <div> I clicked.
<div id="parent" onClick="this.click()">
<div id="1">
<span text="22"></span>
</div>
<div id="2"><span text="32"></span></div>
<div id="3"><span text="232"></span></div>
<div id="4"><span text="242"></span></div>
<div id="5"><span text="252"></span></div>
</div>
I'm at a stage where I get the <div> I have clicked, lets say I have:
<div id="3"><span text="232"></div>
How can I get the id and the value of the text in the <span> inside that <div>?
Add an event handler to the container (#parent) using Element.addEventListener(). When the handler is triggered, check if the event target is a span Element.matches().
If it is, get the id from the parent node (the div), and the text attribute from the span, using Element.getAttribute():
var container = document.getElementById('parent');
container.addEventListener('click', function(e) {
if (!e.target.matches('#parent > div > span')) return;
var id = e.target.parentNode.id;
var text = e.target.getAttribute('text');
console.log(id, text);
});
<div id="parent">
<div id="1">
<span text="22">1</span>
</div>
<div id="2"><span text="32">2</span></div>
<div id="3"><span text="232">3</span></div>
<div id="4"><span text="242">4</span></div>
<div id="5"><span text="252">5</span></div>
</div>
If you are using Jquery, this will work [Tested]:
$("#parent").find('span').each(function(){
$(this).on('click', function(){
console.log($(this).parent().attr('id'));
});
});
Let me know if any issues with this
HTML:
<div id="div1">
<div class="close">close</div>
</div>
<div id="div2">
<div class="close">close</div>
</div>
jQuery:
$('.close').on('click', '#div1, #div2', function(){
console.log ( $(this) ); // .close
});
If I have multiple elements with close buttons, how do I get the parent element as this and not the button?
So if I click the .close on #div1, I need #div1 as this to work with it.
By instinct, I would look to closest, which takes a selector as a param:
var selector = '#div1, #div2';
$('.close').on('click', selector, function(){
console.log ( $(this).closest(selector) ); // .close
});
.closest will return a jQuery object representing first node that matches the selector. It starts with the current object and continues to .parent() until it finds a match
since the element is a child of the element you want to reference, use a parent selector.
$(this).parent().hide()
Most of the time we would use a class on the element and use closest to select it.
$(this).closest('.msg').hide()
$('.close').on('click', function(){
$(this).closest(".msg").hide();
});
.msg{
.border: 1px solid black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1" class="msg">
<div class="close">close</div>
<p>test 1</p>
</div>
<div id="div2" class="msg">
<div class="close">close</div>
<p>test 2</p>
</div>
You actually don't need any selector, just a .closest("div").
If you want to be a bit more specific like "The closest ID starts with div" than you could do like:
$('.close').on('click', function(){
$(this).closest("[id^='div']").fadeOut();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<div class="close">close1</div>
</div>
<div id="div2">
<div class="close">close2</div>
</div>
Or, by doing it the way you started you could use the event.delegateTarget -
which refers to the actual selector-delegators $('#div1, #div2')
$('#div1, #div2').on('click', '.close', function(event) {
$(event.delegateTarget).fadeOut();
});
// or use also for brevity:
// $("[id^='div']").on(...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">
<div class="close">close1</div>
</div>
<div id="div2">
<div class="close">close2</div>
</div>
I am trying to refactor and make a performance wise code.
The idea of the code is to update the id or value of all element with id or value that needs to be updated that happens when an element has been removed / deleted
So what I am trying to do is get all element with Id or value inside a container element (which is possible to be nested in 2 to 4).
At the moment, I am using jQuery to this task. I added a class on every element that has Id and use jQuery .find() to get all of this element using the class I've assign to them .. which is I really hate about my code and wanted to change as well if there's another best way to do it.
So is there a fastest way and performance wise at the same time to do this task?
$("button").on("click", function(){
$($(this).val()).remove();
updateParagraph();
});
function updateParagraph() {
$(".paragraphs").each(function(index, data){
var dataId = data.id.split("-");
var idIndex = dataId[dataId.length-1];
var index = index + 1;
if (index != idIndex) {
dataId.splice(-1, 1);
dataId.push(index);
dataId = dataId.join("-");
$(this).attr("id", dataId);
setChildElementsId($(this), index)
}
});
}
function setChildElementsId(parent, inx) {
$(parent).find(".id-holder").each(function(index, data){
if (data.id) {
var dataId = data.id.split("-");
dataId.splice(-1, 1);
dataId.push(inx);
dataId = dataId.join("-");
$(this).attr("id", dataId);
if(isParagraph(data.tagName)) {
$(this).text(inx);
}
}
else if (data.value) {
var dataValue = data.value.split("-");
dataValue.splice(-1, 1);
dataValue.push(inx);
dataValue = dataValue.join("-");
$(this).val(dataValue);
}
});
}
function isParagraph(tagName){
return tagName == "P";
};
<div id="container-1" class="paragraphs">
<div id="header-container-id-1" class="id-holder">
<h4>Header</h4>
</div>
<div id="paragraph-container-id-1" class="id-holder">
<p id="id-1" class="id-holder">1</p>
</div>
<button value="#container-1" class="id-holder">delete</button>
</div>
<div id="container-2" class="paragraphs">
<div id="header-container-id-2" class="id-holder">
<h4>Header</h4>
</div>
<div id="paragraph-container-id-2" class="id-holder">
<p id="id-2" class="id-holder">2</p>
</div>
<button value="#container-2" class="id-holder">delete</button>
</div>
<div id="container-3" class="paragraphs">
<div id="header-container-id-3" class="id-holder">
<h4>Header</h4>
</div>
<div id="paragraph-container-id-3" class="id-holder">
<p id="id-3" class="id-holder">3</p>
</div>
<button value="#container-3" class="id-holder">delete</button>
</div>
<div id="container-4" class="paragraphs">
<div id="header-container-id-4" class="id-holder">
<h4>Header</h4>
</div>
<div id="paragraph-container-id-4" class="id-holder">
<p id="id-4" class="id-holder">4</p>
</div>
<button value="#container-4" class="id-holder">delete</button>
</div>
<div id="container-5" class="paragraphs">
<div id="header-container-id-5" class="id-holder">
<h4>Header</h4>
</div>
<div id="paragraph-container-id-5" class="id-holder">
<p id="id-5" class="id-holder">5</p>
</div>
<button value="#container-5" class="id-holder">delete</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If I understand your question correctly, you're looking to more elegantly identify which elements have an id of the form "__-id-#" or simply "id-#".
If this is the case, take a look at some more advanced jQuery selectors. One in particular which might meet your needs is the Attribute Contains Selector.
For instance, I think $(parent).find("[id*='id-']") might do what you're looking to do.
While I understand what you're attempting to do, I don't quite understand why you're doing this in the first place.
Unless there are restrictions that force you to structure your HTML like you did, well, don't. Aim for the simplest structure:
<div id="container-123" class="paragraphs">
<h4>Header</h4>
<p>1</p>
<button type="button">delete</button>
</div>
Remove the <div>s around the <h4> and the <p> unless you need them for some styling reason. The <button> doesn't need to know its ID, because it's a child element of the container, so you're delete handler could make use of that fact:
$(document.body).on("click", "button", function() {
$(this).closest('.paragraphs').remove();
});
If there are outside forces that require a specific ID (e.g. for linking to an anchor), keep that on the top container element. If your CSS targets elements by ID, refactor the CSS.
I would like to answer your question using javascript. In fact you don't need any of those id-s
I hope I'm not too late.
let buttons = Array.from(document.querySelectorAll(".id-holder"));
buttons.forEach(b => {
//for each button add an event listener
b.addEventListener("click", () => {
b.parentElement.parentElement.removeChild(b.parentElement);
resetNums();
});
});
function resetNums(){
// reseting the text inside the p
let btns = Array.from(document.querySelectorAll(".id-holder"));
btns.forEach((bt,i)=>{
let theP = bt.parentElement.querySelector("p");
theP.innerHTML = i+1;
})
}
<div>
<div>
<h4>Header1</h4>
</div>
<div>
<p>1</p>
</div>
<button class="id-holder">delete</button>
</div>
<div>
<div>
<h4>Header2</h4>
</div>
<div>
<p>2</p>
</div>
<button class="id-holder">delete</button>
</div>
<div>
<div>
<h4>Header3</h4>
</div>
<div>
<p>3</p>
</div>
<button class="id-holder">delete</button>
</div>
<div>
<div>
<h4>Header4</h4>
</div>
<div>
<p>4</p>
</div>
<button class="id-holder">delete</button>
</div>
<div>
<div>
<h4>Header5</h4>
</div>
<div>
<p>5</p>
</div>
<button class="id-holder">delete</button>
</div>
I have this html structure (very general), the id of the div is added dynamically, by a function that creates sequential objects made this way:
<div id="mydiv1">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
The button "remove" should remove the div where he is, so I have to retrieve the id of the div to do it. I do not know how. How can you make using jQuery? thank you
<form>
<div id="mydiv1">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
<div id="mydiv2">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
</form>
I tried:
("#remove").click(function(event) {
var id = event.target.id;
}
But the result is: "remove" instead of "mydiv1" or "mydiv2"
You should use class instead of id for the buttons (id should be unique):
$('.remove').click(function() {
$(this).closest('div[id^="mydiv"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div id="mydiv1">
<div>Stuff 1</div>
<div>
<button class="remove">REMOVE</button>
</div>
</div>
<div id="mydiv2">
<div>Stuff 2</div>
<div>
<button class="remove">REMOVE</button>
</div>
</div>
</form>
EDIT: Updated to new code posted by OP
For mydiv2 change button like this:
$(".remove").click(function() {
var id = $(this).data('id');
$("#mydiv"+id).remove();
}
<button class="remove" data-id="2"></button>
Use $(this).parent('div') to get the first parent node of type <div>
$("#remove").click(function(event) {
var parent = $(this).parent('div');
parent.remove();
}
EDIT
So add a class to your divs, let say .divRow for example
<form>
<div id="mydiv1" class="divRow">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
<div id="mydiv2" class="divRow">
<div> Stuff</div>
<div>
<button id="remove"></button>
</div>
</div>
</form>
and your javascript would be in this case
$("#remove").click(function(event) {
var parent = $(this).parent('.divRow'),
id = parent.attr("id");
alert(id);
parent.remove();
}
Try
$('.remove').click(function() {
var id = $(this).parent().parent().attr('id');
//This will give you the id
});
For the next part of your question try this:
$(document).on('click','.remove',function() {
var id = $(this).parent().parent().attr('id');
//This will give you the id
});