Here is everything involving the link:
<a class="" data-images="{"detail_url":"//assets.supremenewyork.com/148393/ma/hBwFmRXhVKI.jpg","zoomed_url":"//assets.supremenewyork.com/148393/zo/hBwFmRXhVKI.jpg"}" data-style-name="Black" data-style-id="19033" data-sold-out="false" data-description="null" href="/shop/bags/lkav6jh17/xfdbgpiea" data-no-tubolink="data-no-tubolink"><img width="32" height="32" src="//d17ol771963kd3.cloudfront.net/148393/sw/hBwFmRXhVKI.jpg" alt="Hbwfmrxhvki"></a>
I use nightmare with node coded in atom and would like to click on the black bookbag from the url: http://www.supremenewyork.com/shop/bags/lkav6jh17/p9ylgt8vm
using the "data-style-name="Black" found in the elements.
I've tried:
.click("data-style-name ='Black'")
which gave me the error:
Failed to execute 'querySelector' on 'Document': 'data-style-name ='Black'' is not a valid selector.
Not sure what to do to click but any help would be great. The link is an image and part of a list element on the webpage.
first grab the DOM node and assign to a variable then click on the node. Also you need to add brackets around the selector and don't need the inner single quotes unless there is a space or other invalid character in the value
var myLink = document.querySelector("[data-style-name=black]");
.click(myLink)
Also what I did was:
.click('a[data-style-name="Tan"]')
I specified it was an attribute and it worked.
Related
EXception occur (element not found # given xpath ) when try find element by x path in eclipse project using ie driver in maven project , this element is inside iframe,
when inspect desired element, I found it in the following structure:
<div id="idName">
<div class="container">
<div>
<p class="v1">..............notice this repeated for many different href
<a href=
<span class="v2".........notice this repeated for many different href
<b>part of label</b>
rest of label
<br></br>
When I used
webelement.findElement(By.xpath("//*[#id='idName']/div/div/p/a")).getAttribute("href"))
this results in exception when run No Such Element Exception
, seems I miss something in the relative XPath, any ideas ?
Note: i tried to switch driver to iframe before find element but it didn't help and still having exception .
Thanks A lot for any help .
Based on the HTML provided above best bet would be to go for first anchor tag following the div 'ID' assuming that ID is unique throughout the page you are working on.
Modify the locator as below and give it a try:
//*[#id='idName']//following::a
If this returns more than 1 link in your page then you can add an index at the end as below:
(//*[#id='idName']//following::a)[1]
when the element we want to get it`s attribute exist inside iframe then we shall switch to this frame first :
driver.switchTo().frame("frameid").findElement(By.xpath("element xpath")).getAttribute("href");
then switch to default content to go out of frame:
driver.switchTo().defaultContent();
I am facing a weird issue. I have an a href tag
<a class="link" data-bind="click: templateToUse" href="#" id="InputType"><b>Title:</b> Content</a>
My JS
$('.link').click(function(event){
if(event.target.id!='')
alert(event.target.id);
else
alert('undefined');
});
Fiddle: http://jsfiddle.net/sourabhtewari/ork50uf7/
Now if I click on the bold 'Title', it gives me an empty target Id. I assume that since the whole text is within the a href tag, it should send out the event target id, but incase we have a formatted text in the link, the formatted text wont send the correct event target.
Now, I am sure there is an easy fix for this. Maybe I am using CSS incorectly. I tried using the 'display:block' but this wont help either.
You need to use currentTarget. See MDN for an overview of the different "targets" in an event objects.
Solution:
if(event.currentTarget.id!='')
alert(event.currentTarget.id);
Working fiddle.
I've used a for loop to create a bunch of images with unique ids. They look something like this:
<img src="image.jpg" id="110021002" />
<img src="image.jpg" id="110021003" />
<img src="image.jpg" id="110031002" />
...
Later on in the code I want to select one of the images by ID and remove it. I tried the following:
var removeId = '110021002';
var img = document.getElementById(removeId);
img.parentNode.removeChild(img);
But I get the following error:
Cannot read property 'parentNode' of null
Not quite sure what's going on here. Is it because the images were created dynamically?
Your code works perfect: http://jsbin.com/zexoweyu/3/edit for the first time you remove an element, obvisouly on the second attempt the element is not there and it will throw the given error.
On the fiddle:
Click once, works
Click again, fails because the element with that ID is no longer there.
And yes, ids can start with numbers.
**Attribute ID** Specifies a unique id for the element. Naming rules:
Must contain at least one character
Must not contain any space characters
In HTML, all values are case-insensitive
You can't have IDs that start with a number. Try prefixing them with a letter.
In the simplified code below the href is linked to a custom javascript function (MyFunction). When clicking on the link ('link text') nothing happens (while I'd expect an alert message 'Hello world') and the console shows an error 'Uncaught SyntaxError: Unexpected token !' at the start of the document, which I (also) dont understand.
Just wondering what is wrong in the code below (?)
<script type="text/javascript">
function MyFunction(message){
alert(message);
}
$(document).ready(function(){
var message="Hello world";
$('#myDiv').html('<a id="myLink" href="#" onclick="MyFunction('+message+');">link text</a>'); //looked at the example solution at http://stackoverflow.com/questions/1070760/javascript-function-in-href-vs-onclick
}); //$(document).ready
</script>
</head>
<body>
<div id="myDiv"> </div>
</body>
</html>
You string for the creating of the a tag will evaluate to this:
<a id="myLink" href="#" onclick="MyFunction(Hello world);">link text</a>
So it will be thrown an exception. You can quote the parameter like many people said:
onclick="MyFunction(\'' + message + '\');" // onclick="MyFunction('Hello World!');"
Or you can do it the right way:
$('#myDiv').append('<a id="myLink" href="#">link text</a>').on('click', 'a', function(e)
{
alert(message);
});
In this case, message must be declared in the global scope in order to work. Fiddle.
UPDATE: Now, why I think the second one is better:
The html() method espects the following parameter:
A string of HTML to set as the content of each matched element.
And the append() method accepts as the first parameter:
DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
So you can see that append() espects a DOM element/tree to be appended to the element while html() espects only an string, like innerHTML for pure JavaScript. You just don't add elements to a element with innerHTML, you have to create them, that is what append() does.
Then, as the element is now added to the dom tree, you can set it's events with on() replacing your inline event on the HTML tag. See here or here why.
String literal should be quoted, even inside quoted code. The problem is you need it to be quoted too much: String literal (1) inside attribute (2) inside string with HTML (3).
With such deep nesting different problems arise. I faced them literally yesterday. I didn't finish with exact test case, but it seems, that even using " leads to bugs in Chrome.
Hence I'd suggest a workaround: put a message into the attribute:
$('#myDiv').html(
'<a id="myLink" href="#" ' +
'data-message="' + message.replace(/"/g, """) + '"' +
'onclick="MyFunction(this.getAttribute(\'data-message\'));">' +
'link text</a>'
);
Solution by #DontVoteMeDown is even better, and not only because it "attacks" the problem from completely different direction, eliminating the need of escaping/quoting.
My technique is useful, when one need to have different context for different elements even with attaching event handlers via DOM level 2 / jQuery.
Quote the parameter:
onclick="MyFunction('"+message+"');
Else it looks for a variable with the text from message
You're running into two separate quoting issues at the same time. Currently your code will output this:
<a id="myLink" href="#" onclick="MyFunction(Hello world);">link text</a>
Which isn't correct because JavaScript is going to try to interpret Hello world as objects (notice it has no quotes):
MyFunction(Hello world);
Thus, you need to surround it in quotes. However, if you try that:
'<a id="myLink" href="#" onclick="MyFunction("'+message+'");">link text</a>'
Then the resulting markup won't be parseable:
<a id="myLink" href="#" onclick="MyFunction("Hello world");">link text</a>
Because the double-quotes will confuse it. It'll try to end the onclick attribute at the first parenthesis and then encounter an unexpected Hello token.
(Note the syntax highlighting here on Stack Overflow identifies the problems in both examples.)
So you also need to use single-quotes, and in order to do so in an already single-quoted string, you need to escape them:
'<a id="myLink" href="#" onclick="MyFunction(\''+message+'\');">link text</a>'
I have seen the following href used in webpages from time to time. However, I don't understand what this is trying to do or the technique. Can someone elaborate please?
An <a> element is invalid HTML unless it has either an href or name attribute.
If you want it to render correctly as a link (ie underlined, hand pointer, etc), then it will only do so if it has a href attribute.
Code like this is therefore sometimes used as a way of making a link, but without having to provide an actual URL in the href attribute. The developer obviously wanted the link itself not to do anything, and this was the easiest way he knew.
He probably has some javascript event code elsewhere which is triggered when the link is clicked, and that will be what he wants to actually happen, but he wants it to look like a normal <a> tag link.
Some developers use href='#' for the same purpose, but this causes the browser to jump to the top of the page, which may not be wanted. And he couldn't simply leave the href blank, because href='' is a link back to the current page (ie it causes a page refresh).
There are ways around these things. Using an empty bit of Javascript code in the href is one of them, and although it isn't the best solution, it does work.
basically instead of using the link to move pages (or anchors), using this method launches a javascript function(s)
<script>
function doSomething() {
alert("hello")
}
</script>
click me
clicking the link will fire the alert.
There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.
A cleaner option is to use href="#no" where #no is a non-defined anchor in the document.
You can use a more semantic name such as #disable, or #action to increase readability.
Benefits of the approach:
Avoids the "moving to the top" effect of the empty href="#"
Avoids the use of javascript
Drawbacks:
You must be sure the anchor name is not used in the document.
The URL changes to include the (non-existing) anchor as fragment and a new browser history entry is created. This means that clicking the "back" button after clicking the link won't behave as expected.
Since the <a> element is not acting as a link, the best option in these cases is not using an <a> element but a <div> and provide the desired link-like style.
is just shorthand for:
It's used to write js codes inside of href instead of event listeners like onclick and avoiding # links in href to make a tags valid for HTML.
Interesting fact
I had a research on how to use javascript: inside of href attribute and got the result that I can write multiple lines in it!
<a href="
javascript:
a = 4;
console.log(a++);
a += 2;
console.log(a++);
if(a < 6){
console.log('a is lower than 6');
}
else
console.log('a is greater than 6');
function log(s){
console.log(s);
}
log('function implementation working too');
">Click here</a>
Tested in chrome Version 68.0.3440.106 (Official Build) (64-bit)
Tested in Firefox Quantum 61.0.1 (64-bit)
It is a way of making a link do absolutely nothing when clicked (unless Javascript events are bound to it).
It is a way of running Javascript instead of following a link:
link
When there isn't actually javascript to run (like your example) it does nothing.
Refer to this:
Link to the website opened in different tab
Link to the div in the page(look at the chaneged url)
Nothing happens if there is no javaScript to render
javascript: tells the browser going to write javascript code
Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.
e.g. handler_function(this.id) works as onClick but not as a javascript URL.
Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.
Since it is a styling issue, instead of polluting the HTML with non valid syntax, you could/should use a W3 valid workaround:
Format the HTML properly, without href, following the W3 accessibility guide lines for buttons.
Use CSS to fix the initial goal of applying a clickable UX effect on a control.
Here's a live example for you to try the UX.
HTML
<a role="button" aria-pressed="false">Underlined + Pointer</a>
<a role="button" aria-pressed="false" class="btn">Pointer</a>
CSS
a[role="button"]:not([href]):not(.btn) { text-decoration: underline; }
a[role="button"]:not([href]) { cursor: pointer; }
I was searching for a solution that does not refresh pages but opens menu items on Ipads and phones.
I tried it on also mobile, It works well
Dr
1. Use that java script to Clear an HTML row Or Delete a row using the id set to a span and use JQuery to set a function to that span's click event.
2. Dynamically set the div html to a string variable and replace {id} with a 1 or 2 etc. cell of a larger div table and rows
<div class="table-cell">
<span id="clearRow{id}">
Clear
</span>
</div>
<div class="table-cell">
<span id="deleteRow{id}">
Delete
</span>
</div>
//JQuery - Clear row
$("#clearRow" + idNum).click(function(){
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
$("someIDOrWildcardSelector" + idNum).val("");
});
//JQuery to remove / delete an html row
$("#deleteRow" + idNum).click(function(){
//depending upon levels of parent / child use 1 to many .parent().parent().parent()
$(this).parent().remove();
});