Get Element in Div JS - javascript

I want to create an onclick function for button that is in div with id Restyled.
I tried this:
<script>
var RestyledDiv = document.querySelector("#Restyled");
var RestyledButton = x.querySelector("button");
RestyledButton.onclick = function() {
alert("button was clicked");
}​;​
</script>
But I get this error: Uncaught SyntaxError: Invalid or unexpected token

You're looking for adding an event listener to the button and you can use the querySelector to go deeper than just a single selector level.
You also had two hidden whitespace characters in your code that resulted in the syntax error you were seeing.
Note the <0x200b> characters that are shown in my editor that is configured to show whitespace characters.
var RestyledButton = document.querySelector("#Restyled button");
RestyledButton.addEventListener('click', function() {
alert("button was clicked");
});
<div id="Restyled">
<button>Click me!</button>
</div>

i tried running your code and basically there are 2 things that i would like to point out:
var RestyledDiv = document.querySelector("#Restyled");
it is not needed here, you are not using the given div.
You can directly select the button by the provided id. You can delete the dive query line whatsoever.
it seems like there was something weird in your last line of code:
}​;​
For some reason, it was not working for me, but as soon as i literally retyped the same code - it worked.
Here's how it works for me:
<script>
var RestyledButton = document.querySelector('#restyledButton');
RestyledButton.onclick = function () {
alert('button was clicked');
};
</script>

Related

Am I missing a cast with querySelector('#element')?

I couldn't find identical answer to my question, so I decided to ask it by myself.
Im trying to select a HTML element with a specified ID in it.
This version works fine.
var button = document.getElementById('#submit');
function doSmth(){
console.log("clicked");
}
button.addEventListener('click', doSmth);
If I try to run the same code with querySelector:
var button = document.querySelector('#submit');
I get the following output:
Uncaught TypeError: button.addEventListener is not a function
Any ideas why same code outputs different return values?
This is the submit input field. It is part of the div container
<input id="#submit" type="submit">
Since the id have # use \\ to escape it
var button = document.querySelector('#\\#submit');
function doSmth() {
console.log("clicked");
}
button.addEventListener('click', doSmth);
<input id="#submit" type="submit">

onClick not working for my button

I'm creating a website where I'll be displaying my work. Then I noticed that I needed a Cookie Notice. Because I want to make it 100% by myself (without generators, etc.) I started creating it. The Cookies themselves are working fine, but main.js is not registering the button's onClick.
Here's the code:
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
My button's code:
<button id="cookieAccept" class="cookieButton">Accept</button>
I've been Googling a lot, searching through StackOverflow, etc. There are no answers that worked for me (yet). Here are the solutions I tried:
jQuery
object.onclick = function() {}
object.addEventListener("click", false);
Put the object.addEventListener("click", false) inside of window.onload
Any hints/help?
- XaafCode
EDIT
Console error:
Uncaught TypeError: Cannot set property 'onclick' of null
The possible reason in this case would only be is.
This will work
<button id="cookieAccept" class="cookieButton">Accept</button>
<script>
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
</script>
Make sure you don't have Js before html is written. First html then Js. Also make sure you don't have two id of same name . This may some time create problem.
This will not work
<script>
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
</script>
<button id="cookieAccept" class="cookieButton">Accept</button>
Be sure to wrap your js code in a function that you'll register to be executed once the browser sets up all the html:
window.onload = function() {
var acceptButton = document.getElementById("cookieAccept");
acceptButton.onclick = function() {
alert("HELLO");
}
}
Cfr.: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload
Remember to put HTML code before Javascript syntax under tag.

CasperJS click is leads to error even when the element exists

I'm trying to click on a logout button, which I have retrieved from the current page. I successfully got the id of the logout link. But when I click on it, an error occurs
Cannot dispatch mousedown event on nonexistent selector
function getLogoutId()
{
var logoutid = "";
$(document).find("a").each(function(key,value){
var id = $(this).attr("id");
if(id.toLowerCase().indexOf("logout") > -1)
{
__utils__.echo("insidelogout" + id);
logoutid = id;
}
});
return logoutid;
}
var logoutid = this.evaluate(getLogoutId);
fs.write("logout.txt", this.getHTML(), 'w');
this.thenClick("#"+logoutid, function(){});
I have written the html content to a file, in which I checked for the id and it is there. The id attribute in question looks like this:
et-ef-content-ftf-flowHeader-logoutAction
I see nothing wrong with your code aside from strange usage of jQuery.
You can try other CSS selectors for clicking:
casper.thenClick("[id*='logout']"); // anywhere
or
casper.thenClick("[id$='logoutAction']"); // ending
or
casper.thenClick("[id|='logoutAction']"); // dash-separated
Maybe it is an issue with the code that follows the shown code. You can try to change thenClick to click.
Have you tried using just this.click("#"+logoutid);?
Also have you considered using jQuery to click on the button? Something like this...(first make a variable of your id so you can pass into jQuery).
var id = "#"+logoutid;
this.evaluate(function(id){
jQuery(id).click();
},id);

Works locally but not online

I have it so when you click on the elements such as the top right one hydrogen it plays a video in the big center div and displays info about hydrogen. I got it to work locally but i am unable to get it to work online.
Please any help would be great.
Here is the link to my project
http://travismichael.net/periodic_elements/
Here is the script for my site
<script type="text/javascript">
$(document).ready(function() {
$('div.video').hide();
$('.icon').click(function(){
var id=$(this).data('id'),
thisDiv=$("div.video[data-id='" + id +"']"),
thisVideo=$("div.video[data-id='" + id +"']").find('video');
$('video').each(function() {
this.pause();
this.currentTime = 0;
});
$('div.video').not(thisDiv).fadeOut('fast');
thisDiv.fadeIn();
thisVideo.get(0).play();
});
});
</script>
<script type="text/javascript">
$("#periodictable td").hover(function() {
$(this).stop().animate({opacity: "1"}, 'fast');
},
function() {
$(this).stop().animate({opacity: ".7"}, 'slow');
});
</script>
Error is here:
You're trying with
var thisDiv = ("div.video[data-id='" + id +"']");// but it returns jQuery object,
// not element
// Thats why below statement will not work
// because it works on element
alert(thisDiv.nodeType);
So you should try like this:
var thisDiv = ("div.video[data-id='" + id +"']")[0]; // returns the element
alert(thisDiv.nodeType); // and then get the nodeType
When checked I get an error message that says the Element is undefined.
you should past the error your console is giving you, as it is going to give much more explanation to what you are looking for.
It is obviously throwing an exception and whatever your exception is is displaying the error message, so...you try it on your local host where the files are defined. Are they declared in your code with a pointer or something to say go look back here and use this when the button is clicked?
It looks like your function should contain these declarations, or you could make them global, not really sure without more info...

jQuery Click Event Triggering without Clicking

I am facing a tricky problem with my code and hope to get some help on this. Below is a snippet of my code:
<SCRIPT type='text/javascript'>
function list(json) {
// list result
$('#pop-up').click(alert(json.length));
}
// declare map and options
google.maps.event.addListener(map, 'idle', function () {
var query = 'some query';
$.getJSON(query, list);
});
</SCRIPT>
<A href='javascript:void(0)' id='pop-up'>Click Me</A>
As seen, the pop-up is supposed to return the length of json object when the pop-up link is clicked. However, I am getting the pop-up without clicking the link. Anyone knows where the problem lies?
It's because you're using .click() rather than .click(function() {}). Replace the $('#pop-up') line with:
$('#pop-up').click(function() { alert(json.length) });
and get rid of the curly brace underneath that line.

Categories

Resources