Can't get button to disappear - javascript

I am trying to get this button to disappear when it is clicked, however, it does nothing when clicked
HTML
<button id="startButton" onclick="startButton()">
<img src="Img\MainMenu\button(play).png">
</button>
<script type="text/javascript" src="Client\js\placeholder.js"></script>
JavaScript
startButton.onclick = function startButton() { // when start button is clicked
startButton.style.display = "none";
};

You should learn a bit more about HTML and JavaScript before you start coding. Your code has some fundamental errors.
To reference an element uniquely in JavaScript, you'll need to use document.getElementById:
The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.
If you need to get access to an element which doesn't have an ID, you can use querySelector() to find the element using any selector.
Source: MDN
<button id="startButton">
<img src="Img\MainMenu\button(play).png">
</button>
<script>
const $startButton = document.getElementById('startButton')
$startButton.onclick = () => {
$startButton.style.display = 'none'
}
</script>

Related

How to click on a custom attribute in selenium?

I have this following html:
which has a class and a custom attribute, I have several header's with the same className. I wanted to know how to uniquely get this element and click on it.
<h4 class="font-white topic-heading progress-header no-margin width-80 d-table-cell" data-collapse-id="1">I. Introduction</h4>
This is what i tried:-
I tried to get the attribute of the class="font-white..." with data-collapse-id="1" :
var element = driver.findElement(By.xpath("//*[#class='font-white topic-heading progress-header no-margin width-80 d-table-cell']")).getAttribute('data-collapse-id="1"');
console.log(element); // this prints a promise.
element.click(); //element.click is not a function exception
I also tried:-
var element = driver.findElement(By.xpath("//*[#data-collapse-id='1']"));
element.click(); // element.click is not a function exception.
I wanted to know how to fetch this element in selenium and click on it.
this is the entire div:
<div class="page-width d-table topic-heading-div">
<h4 class="font-white topic-heading progress-header no-margin width-80 d-table-cell" data-collapse-id="1">I. Introduction</h4>
<i class="fa fa-check font-white font-18 width-20 d-table-cell text-center vertical-center" aria-hidden="true"></i>
</div>
Did you try:
driver.findElement(By.cssSelector("h4[data-collapse-id='1']")).click();
Finding element through this attribute should work because this is unique. Also it sometimes unable to click on element found by xpath. I think this should work
It seem that your element variable intends to return attribute. However, getAttribute() method should receive attribute name value as argument and return an attribute value which is a simple string... And here you got few problems:
you're trying to pass wrong argument: 'data-collapse-id="1"' instead of 'data-collapse-id'
attribute value, a string, is not clickable!
Simple answer to your question- there is no way you can click on a custom attribute
Class is meant to define a group of elements having similar features. In this case, the topic-heading class is used to group the <h4> tags alongwith a unique ID attribute called as data-collapse-id. But in such case's we can't use ID to identify/specify each web element as the elements of same class can be hundreds/thousands.
You can try locating any header element uniquely using the following ways:
var exactHeadingText = "I. Introduction"; // Exact heading
By locExactTopicHeading = By.xpath("//h4[contains(#class,'topic-heading') and text()='"+ exactHeadingText + "']");
var partialHeadingText = "Introduction"; // Partial heading
By locPartialTopicHeading = By.xpath("//h4[contains(#class,'topic-heading') and contains(text(),'"+ partialHeadingText + "')]");
Ideally you should pass the exactHeadingText/partialHeadingText as a function parameter/argument so that the code can be reused to fetch any topic heading.
You can then use findElement() and perform any operation on it.

Getting Element

I am new to this and I have this element and I have to somehow "get it". There are few more element above it, there's just an element I need:
<a class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
Thanks for help!
$('a.btn_green') will return an array of you could use the Array index to access the proper value if the index is known and does not change
var $a = $('a.btn_green');
var el = $a[2];
You can use getElementsByClassName.
document.getElementsByClassName('btn_green')
This will return an array of all the elements that match. If you have only one element you can access it at index 0.
document.getElementsByClassName('btn_green')[0]
If you added an ID to the element,and then use getElementById
<a id="YOUR_ID_HERE" class="btn_green" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
document.getElementById('YOUR_ID_HERE')
You can do something like this in standard JS you would do something similar to this:
var button = document.getElementsByClassName('btn_green');
If you're just looking to get that specific element I would suggest adding an id
<a class="btn_green" id="myButton" href="javascript:void(0)" onclick="ShowPopup( 440, "some_text", "some_text" ); return false;">
<span>Some text</span>
</a>
And here is the JS
var button = document.getElementById('myButton');
Details are commented in the Snippet. The anchor in OP's code is atrocious so I made the markup simpler, but the code provided here will work an any anchor(s) under certain conditions described below.
SNIPPET
/* Plain JavaScript */
/* If there is only one element that has the class="btn_green" */
// By className
var btnByClassName = document.querySelector(".btn_green");
/* If it is the only link (anchor)
*/
// By tagName
var btnByTagName = document.querySelector("a");
/* If theres more than one element with the class="btn_green" */
// By className
var btnsByClassName1 = document.querySelectorAll(".btn_green");
// or
var btnsByClassName2 = document.getElementsByClassName("btn_green");
/* The two methods above will collect all elements with the
specified className. The group of elements collected is known
as a HTML Collection or NodeList. If you need to specifically
target one of them out of a group, say like the 2nd one, you have
to count from 0. Ex. the second element in a NodeList would be 1.
*/
/* Continuing from the previous example above, we can single out a
single element by placing the 0 count number of that element:
*/
var btnsByClassNameA = document.querySelectorAll(".btn_green")[1];
//or
var btnsByClassNameB = document.getElementsByClassName("btn_green")[1];
/* A different type of NodeList/HTML Collection can be had by
targeting the tagName, this example we are targeting the first
anchor:
*/
var btnsByTagName1 = document.querySelectorAll("a")[0];
//or
var btnsByTagName2 = document.getElementsByTagName("a")[0];
/* Note: Although these methods are able to get a group of
elements, they are able to get an element if it is the only
one of it's kind by using [0].
*/
/* jQuery */
/* jQuery makes it easier and does most of the thinking for us.
You must make sure that your page has the jQuery library loaded.
Look at the HTML section below, you'll see a <script... tag. You
must have that tag inside the <head></head> or before the </body>
otherwise you code will not function.
*/
/* Note the variable has a $ prefix. This is optional and it's
purpose is to show other developers that the variable represents a
jQuery Object.
*/
// By className
var $btnsByClassName = $(".btn_green");
// By tagName
var $btnsByTagName = $("a");
/* This part is not part of the question, it is just to show that
these references are working */
$btnsByTagName.on('click', aTonOfStuff);
function aTonOfStuff() {
btnByClassName.style.backgroundColor = "black";
btnByTagName.style.color = "lime";
for (let i = 0; i < btnsByClassName1.length; i++) {
btnsByClassName1[i].style.fontSize = "40px";
btnsByClassName2[i].style.fontVariant = "small-caps";
}
btnsByClassNameA.style.backgroundColor = "#0E0";
btnsByClassNameB.style.color = "#000";
btnsByTagName1.style.lineHeight = "2";
btnsByTagName2.style.textDecoration = "overline";
$btnsByClassName.fadeOut("slow");
$btnsByTagName.fadeIn("slow");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Click any link.</p>
<a class="btn_green" href="#/">First Green Button Anchor Link</a>
<a class="btn_green" href="#/">Second Green Button Ancor Link</a>
Something like $('a.btn_green') would "get" that <a> element but it is not guaranteed to get it uniquely. You may need to use something like the :nth-child pseudo-selector to do this if you cannot modify the source. Without more context it is impossible to say what a selector would be that would uniquely retrieve either the <a> or the <span> element.
Here is a jQuery tutorial and here is a CSS selector reference, just in case you need them.
Edit
One weird thing happening on the page is $ no longer seems to be bound to jQuery. They must be loading something which uses $ after jQuery which is causing selectors like $('a.btn_green') to return null. You can replace $ with jQuery instead.
I tried the using jQuery('.btn_green_white_innerfade.btn_medium') to find the element, but it looks like there are three elements on the page which share that selector. So I looked further up in the source and found that the button I think you want is within a div with the id market_buyorder_info. This led me to the following code to get the element uniquely:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium')
And this code to trigger a click in the console:
jQuery('#market_buyorder_info').find('.btn_green_white_innerfade.btn_medium').click()

Get reference of object inside of div

I'm trying to reference an object inside of a div, using plain JavaScript:
<div id="main">
<div id="search">
<input type="text" id="query" />
<button onclick="test()">OK</button>
</div>
</div>
<script>
function test() {
try {
var main = document.getElementById("main");
var search = main.getElementById("search");
alert(search);
} catch (e) {
alert(e);
}
}
</script>
But I keep getting this error:
TypeError: main.getElementById is not a function(…)
Referencing main works, but not what's inside of main.
I also set up a Fiddle.
To find an element inside of other use querySelector
document.querySelector('#main #search')
As ID is unique, you can directly use
document.getElementById('search')
The reason for the error is there is no method called getElemetnById() attached to the Element object.
Since ID of an element must be unique there is need to do that, just use document.getElementById().
But if you want to make sure the said element is a descendant of anotehr element you can use document.querSelector('#main #search')
DOM Elements don't have getElementById method. Only document object have this method.
Id attribute specifies a unique id for the element.
It means only one element can have id="search". So you can use document.getElementById("search");

How to change onclick attribute on html file?

I have a progress bar and want to change it's data-pro-bar-percent attribute value from 80 to 100 when I click a link.
The attribute change should be as follows:
data-pro-bar-percent="80" --> data-pro-bar-percent="100"
This is the HTML:
<a class="button" href="#">Click Link</a>
<div class="pro-bar-container color-green-sea">
<div class="pro-bar bar-100 color-turquoise" data-pro-bar-percent="30" data-pro-bar-delay="4000">
<div class="pro-bar-candy candy-ltr"></div>
</div>
</div>
Links are not buttons! Use buttons!
Use the DOM's setAttribute method to alter the data attribute. This is tricky though, you can either grab the percent element by its classname (if it shares a class name with another element, you may want to use this.children.children.setAttribute()) so grab the closest nested child you want.
Simply set the link/button element an eventListener (if it's in a form, a button acts like a submit button by default, so you may need to prevent the default action), and give it a function to change the data attribute.
<button id="myButton">Click Me</button>
var button = document.getElementById("myButton");
button.addEventListener("click",function() {
document.getElementsByClassName("pro-bar")[0].setAttribute("data-pro-bar-percent","100");
}, false);
As #rlemon commented, getElementsByClassName lacks the support that querySelector does, so you should use that instead.
document.querySelector(".pro-bar").setAttribute("data-pro-bar-percent","100");
You should use .data() instead of .attr() to get the current data value and then set it as well. Much more efficient.
http://api.jquery.com/data/
$('.button').on('click', function(){
var current = $('.pro-bar').data("pro-bar-percent");
$('.pro-bar').data("pro-bar-percent", current += 20);
});
You can use jQuery, first give an id to your link:
<a class="button" id="btnLink" href="#">Click Link</a>
Now, use this, if you directly want to change the value of data-pro-bar-percent to 100.
$("#btnLink").on("click",function(){
$(".pro-bar .bar-100 .color-turquoise").attr("data-pro-bar-percent","100");
});
If you just want to increment the value of the current bar by 20 then use this:
$("#btnLink").on("click",function(){
var targetEle = $(".pro-bar .bar-100 .color-turquoise");
var currentBar = parseInt(targetEle.attr("data-pro-bar-percent"))+20; // whatever value you want to increment with.
targetEle.attr("data-pro-bar-percent",currentBar);
});
Hope this helps

Accessing elements inside dynamically created divs with HTML/Javascript

I'm quite new to javascript and JQuery programming. Usually, to access elements I give them an id, so I can get them like $("#"+id).blabla().
But now I need to dynamically create a div, and access elements inside it.
Something like
<div id="automaticallyGeneratedId">
<div ???></div> <!-- first div -->
<div ???></div> <!-- second div -->
</div>
What are the best practices to access and identify each of the inner divs?
I generate another id for them?
Or what?
I don't have the theory of selectors fully clear.
edit: modified the question from identifying a single inner div to identifying divs amongs many of them
You can maintain a pattern when you're generating id. For example:
if you always generate id like: myid1, myid2,myid3...
<div id="myid1">
<div></div>
</div>
<div id="myid2">
<div></div>
</div>
......
then you can try:
$('div[id^=myid]').find('div').foo();
OR
$('div[id^=myid] div').foo();
Here, ^= is start with selector, so div[id^=myid] will select div whose id start with myid.
You can also use Contain word selector which is ~= and use like $('div[id~=myid]'). This will select div with id contains word myid.
Instead of id if you want to use other attribute eg. name then change selector like:
$('div[name^=myid]') or $('div[name~=myid]').
It's usually a good practice that if you already have a reference to that outer div to just search from there using find.
You can give it an id, or if you want to use a more general approach you can use classes.
<div class="subdiv">...
$('#automaticallyGeneratedId').find('div.subdiv')
Usually, when you create them, you can assign event handlers and the likes straight on them. Like this:
var div = $( '<div></div>' );
div.on( 'click', function() {
// Do something when the generated div is clicked
});
// Then, add it to the DOM
$( 'body' ).append( div );
You don't need to bother selecting them with ID or classes, they're already available in your code.
Another way is to use event bubbling to handle newly created elements of the same class. A good link about this is this one: http://beneverard.co.uk/blog/understanding-event-delegation/
Many ways you can create an element and give him an Id or Class, or use the DOM to access it..
$("html").prepend('<div id="foo"></div>');
$("#foo").doSomething();
another way
$("#automaticallyGeneratedId").find("div").doSomething();
To access the div in the element with the id:
$("#automaticallyGeneratedId div").whatever
If you cache the divs you could use something like:
var myDiv1Child = $('div', myDiv1);
Create a delegated listener and within the listener you can find the element by doing this
//If a div inside the parent is clicked then execute the function within
$('.PARENT_CLASS').click("div", function(){
//This variable holds all the elements within the div
var rows = document.querySelector('.PARENT_CLASS').getElementsByTagName('div');
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function() {
console.log(this); //The element you wish to manipulate
}
}
});

Categories

Resources