How to get element by javascript function - javascript

Can I select the element by its function?
for example
HTML
<button id="saveButton" onClick="javascript:fnSave(this)>
Save
</button>
then javascript
function fnSave(element){
console.log($(element).attr('id'));
}
clicking the button will result : saveButton

You can do that with using the currentTarget - like this:
save = function(object){
console.log($(object).attr('id'));
}
And, you would call this from your HTML like you mentioned - just including the quote:
<button id="saveButton" onClick="save(this)">Save</button>

To get the element you can do what you just did, add onClick='fnSave(this)' to the button, and on the function:
function fnSave(element){
//the element is in 'element'
}
But I see you are using jQuery, so you can remove the onClick and use this:
$("#saveButton").click(function(event){
var element = $(this);//the element is in 'element'
});
Note: if you are going to use this for multiple different buttons, it would be wise to select them by a clasName instead, or use the first function.
edited

Related

Get data of specific node element on click

I'm trying to get specific data depending on which node element the user is clicking. I have 4 elements that I have targeted using the querySelectorAll code. What I want to accomplish is that if I click the first element I will console.log that specific data, and if I select the third element I will get that data logged. I've tried a couple of things, but haven't got it to work yet.
function selectedSplit() {
var macroSplits = document.querySelectorAll(".card");
console.log(macroSplits[0].childNodes[3].childNodes[1].innerHTML);
}
It's unclear where you are using selectedSplit - Wether or not it is being used as the event listener return function. But using an onClick event listener, you're return function will be passed the information you need.
If you want to accomplish this in the markup, you could do -
<div class='card' onClick="selectedSplit"></div>
Then you can simply access it via event.target
function selectedSplit(event) {
var thisCard=event.target;
console.log(thisCard.innerHTML);
}
event.target has the clicked element:
d.onclick = e => console.log(e.target)
<div id=d>
<button><b>b</b></button>
<button><i>i</i></button>
<button><u>u</u></button>
<button><s>s</s></button>
</div>

How to add event listeners using a for loop to dynamically generated buttons

I have a page w/ dynamically generated buttons and i'm trying to add event listeneners to them using a for loop.
I'm not sure why my code is not working as it refers the each button via it's ID and uses dot notation to add the event listener. There is some commenting in the code to help clarify.
Here is abbreviated markup showing the buttons only
<button class="btnRollDice" id="btnRollDiceP1">Roll Dice!</button>
<button class="btnRollDice" id="btnRollDiceP2">Roll Dice!</button>
<button class="btnRollDice" id="btnRollDiceP3">Roll Dice!</button>
Here is the js
rollDiceBtns = document.getElementsByClassName('btnRollDice');//returns a HTML collection
function addEventListeners(){
console.log(rollDiceBtns);
for(i=0;i<rollDiceBtns.length;i++){
console.log(rollDiceBtns[i].id); //THIS WORKS,
rollDiceBtns[i].id.addEventListener('click', rollDice, false); //THIS DOES NOT
}
}
How would this be done using a for loop? to dynamically generated buttons?
addEventListener is a method you find on elements.
rollDiceBtns[i] is an element.
rollDiceBtns[i].id is a string.
Remove .id.

JQuery how to get nested id inside onclick function

<button class="button" onclick="$('#4').popover('show')">Click me</button>
I have some code like above code snippet. I just need an id to pass into the onclick event.
The actual id I want to use is this button sibling's id, which I could get through
$(this).prev().attr('id')
I want to know how to replace #4 with #$(this).prev().attr('id'). Any thoughts?
Thanks Rayon! I got the answer - super straightforward!
$(this).prev().popover('show')
You can try with .parent()
Something like this:
$(this).parent('#parentId')
...if it's parent, or they are on the same level?
Of course, you can write some script where you can create variable for this parent id so you can write:
var parentID = $(this).parent('#parentId');
then you can write:
$(parentID).popover('show')
For siblings you can use:
$(this).siblings( "#siblingId" )

How to simulate a mouse click in Javascript

I have the following elements:
<input type="submit" name="add" value="add item" class="btn btn-add" onclick="addItem('add');return false;">
I want to write a Javascript to simulate a click of a mouse to add item to my shopping basket
I know you can use document.getElementById('add').click() but there's no Id here
I am very new to this and any help would be much appreciated
If you only have on element with name "add" you can also use:
document.getElementsByName('add')[0].click()
You can use Jquery library https://jquery.com
and in the code:
$( "input[name='add']" ).click();
Try using below javascript code.
document.addEventListener("click", function(){
document.getElementById("ID").innerHTML = "Click Event";
});
Get the element by class
var elem = document.getElementsByClassName('btn-add');
Then call click on it
elem[0].click()
Here are some possibilities
document.getElementsByName("add")[0].click();
where 0 is the first element on the page named add.
var form = document.getElementsByTagName("form")[0]; // change 0 to reflect the form
form.elements[form.elements.length-1].click(); // clicks the last button in the form
Alternative
document.forms[n].elements[m].click();
where n is the 0 based index of the form on the page and m is the 0 based index of the element in that form
You might want to use jQuery for this.
Using jQuery you can trigger a click like this:
$('#id').trigger('click');
In case you don't have an id but do have a class it might look like this:
$('.btn-add').trigger('click');
And of course with jQuery you can look at the parent dom element and 'find' the element you are looking for. eg:
$('#parentElement').find('button').trigger('click');
kudo's to mplungjan who came with:
$("input[name='add']").trigger('click');
another way you can find here:
see the fiddle

I need to pass two elements to an onclick event handling function JavaScript and not just their id's

Suppose I have two elements in my code and I want to pass their respective id's to an event handling function. (In my example below, I have a div and a button)
<div id="div1">
<input type="button" id="button1" onclick="doSomething(this, [here comes id of div])" />
</div>
For the button, instead of writing the id which is "button1", I simply passed the element itself using the this keyword. Now my question is, is there a way where I can pass the div element itself in the function and not just its id just like what I did with the button element?
Any help would be greatly appreciated.
You can use the parentNode property;
this.parentNode
As this returns a DOMElement (similar to this), you can access the ID the same via;
this.parentNode.id
... should you want to.
Just get it from the parent in the callback:
function clickHandler(e){
console.log(e.target.parentNode.id);
}
Why do you need to pass it in the first place? Access the div via parentNode.
onclick="doSomething(this);"
and
function doSomething(btn) {
var div = btn.parentNode;
}

Categories