How to get attribute ID to parameter of function js - javascript

I need put 5 images on page like thumbnail, and after click show the lightbox. I need put ID of element what I create to function like parameter. But i cant get ID. I was looking for this problem here and with google but nothings work :( It is project to school and I can use only html, css and javascript, I can not use jquery. Thanks. Here is my code:
function onloadpg() {
for (var i = 0; i<5; i++) {
x[i] = document.createElement("IMG");
x[i].setAttribute("src", "images/" + (i+1) + ".jpg");
x[i].setAttribute("width", "250");
x[i].setAttribute("height", "200");
x[i].setAttribute("alt", fotky.title);
x[i].setAttribute("title", fotky.title);
x[i].setAttribute("id", i+1);
x.setAttribute("onclick", zobraz(x.getAttribute('id')), nacitaj(x.getAttribute('id')));
}

Problem :
You could see in the browser console the message :
Uncaught TypeError: x.setAttribute is not a function
Solution :
You need to use x[i] instead of x to target the current element by index in :
x.setAttribute("onclick", zobraz(x.getAttribute('id')), nacitaj(x.getAttribute('id')));
^________________________________^______________________________^
Should be :
x[i].setAttribute("onclick", "zobraz("+x[i].getAttribute('id')+")", "nacitaj("+x[i].getAttribute('id')+")");
^^^^_________________________^_______^^^^^^___________________^^^^___________^^^^^^___________________^^^^^
Note also that you've to add quotes " and concate variables.
NOTE : You should define the variable x as array :
var x = [];
Hope this helps.
function onloadpg() {
var x = [];
for (var i = 0; i < 5; i++) {
x[i] = document.createElement("IMG");
x[i].setAttribute("src", "images/" + (i + 1) + ".jpg");
x[i].setAttribute("width", "250");
x[i].setAttribute("height", "200");
x[i].setAttribute("alt", "fotky.title");
x[i].setAttribute("title", "fotky.title");
x[i].setAttribute("id", i + 1);
x[i].setAttribute("onclick", "zobraz("+x[i].getAttribute('id')+")", "nacitaj("+x[i].getAttribute('id')+")");
document.body.innerHTML += x[i].outerHTML+"<br>";
}
}
function zobraz(id) {
alert('zobraz : '+id);
}
function nacitaj(id) {
alert("nacitaj : "+id);
}
onloadpg();

function onloadpg(element_id) {
var elem = document.getElementById(element_id);
for (var i = 0; i<5; i++) {
x[i] = document.createElement("IMG");
x[i].setAttribute("src", "images/" + (i+1) + ".jpg");
x[i].setAttribute("width", "250");
x[i].setAttribute("height", "200");
x[i].setAttribute("alt", fotky.title);
x[i].setAttribute("title", fotky.title);
x[i].setAttribute("id", i+1);
x.setAttribute("onclick", zobraz(x.getAttribute('id')),nacitaj(x.getAttribute('id')));
}
onloadpg("element_id");

Related

js.executeScript doesn't work when using getElementsByClassName in selenium

I have a method:
public void delayToCapture(String methodGetBy, String key){
/* List of methodGetBy:
* 1. getElementById
* 2. getElementsByTagName
* 3. getElementsByClassName
* 4. querySelectorAll
*/
System.out.println("Excuteing javaScript...");
if(methodGetBy.equals("getElementById")){
js.executeScript("setTimeout(function(){ document." +methodGetBy+ "('" +key+ "').setAttribute('style', 'display: none');},500);");
}
else if(methodGetBy.equals("getElementsByClassName")){
js.executeScript("setTimeout(function(){"
+ "var elems = document.getElementsByClassName('"+ key +"');"
+ "for(var i = 0; i < elems.length; i++){"
+ "elems[i].style.display = 'none';}"
+ "},"
+ "500);");
}
}
And I call that method in another class:
delayToCapture("getElementsByClassName", "positionmenu");
When running the code, console always show me this message:
java.lang.NullPointerException
However, if I run this code at below on console of Brower directly -> It's work:
setTimeout(function(){
var elems = document.getElementsByClassName('positionmenu');
for(var i = 0; i < elems.length; i++){
elems[i].style.display = 'none';
}
},500);
So, could you tell me what is the reason here?
Try using this :
else if(methodGetBy.equals("getElementsByClassName")){
List<WebElement> element = driver.findElements(By.className(key)); // getting element using class name
js.executeScript("setTimeout(function(){"
+ "var elems = arguments[0];"
+ "for(var i = 0; i < elems.length; i++){"
+ "elems[i].style.display = 'none';}"
+ "},"
+ "500);", element);
}
Hope that helps you.

JSON - How to give onclick element in script?

How to give onclick function for id in JavaScript? eg: my onclick function is oclick="function('#id')" and I need action to be made in div. My each buttons contain their own id's. But I couldnt figure out how to use this element to generate using JSON.
I prefer JavaScript rathar than jquery.
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<button onclick="function('#' + arr[i].ids + '')">' +
arr[i].blaah + '</button><br>';
}
document.getElementById("id01").innerHTML = out;
}
Do you need something like this?
var arr = ["id1", "id2", "id3", "id4"]
function onClick() {
alert("you clicked button with id: " + this.id);
}
function createButtons(arr) {
var out = document.getElementById("out");
for (var i = 0, l = arr.length; i < l; i++) {
var node = document.createElement("button");
node.id = arr[i];
node.innerHTML = "button " + arr[i];
node.addEventListener("click", onClick, false);
out.appendChild(node);
}
}
createButtons(arr);
<div id="out">
</div>
Simple solution: use this
function yourfunction(elem){
//elem contains the button
//you could do:
elem.style.display="none";
}
In your html do:
<div onclick="yourfunction(this)">Button</div>
For shure this can be created dynamically.
If you want to keep your code, dont get confused with " and ' .
" ' " for example: the second " closes the first, even if theres an opened '. And you cannot name a function function. Thats an syntax error. Do this:
"<button onclick=\'func('#elem')\' >test</button>";

Is this the correct way to use two loops in JavaScript

I am trying to check two things here, with two different for loops. One if a element has a attribute, that works! And the second loop should check if the alt tag is actually empty. I figured passing the first iterator value to the second would dispatch the second loop. But that doesn't work! Can someone help me out with this one?
function altChecker() {
var doc = document,
getStartedBtn = doc.getElementById('getStartedBtn');
EventUtility.addHandler(getStartedBtn, 'click', function() {
var all = doc.getElementsByTagName("IMG");
console.log('success!');
for (var i = 0, max = all.length; i < max; i++) {
if (all[i].hasAttribute('alt')) {
console.log('Yes, this has a ' + all[i].nodeName + ' tag!');
} else {
console.log('Sorry ' + all[i].nodeName + ' tag, doesn\'t have an alt tag!');
}
}
for (var j = i, max2 = all; j < max2; j++) {
if(! $(all[j]).attr('alt')){
console.log('This is empty');
} else {
console.log('This aint');
}
};
});
}
I don't think 2 loops are required
function altChecker() {
var doc = document,
getStartedBtn = doc.getElementById('getStartedBtn');
EventUtility.addHandler(getStartedBtn, 'click', function() {
var all = doc.getElementsByTagName("IMG");
console.log('success!');
for (var i = 0; i < all.length; i++) {
if (all[i].hasAttribute('alt')) {
if (all[i].alt === '') {
console.log('this has a ' + all[i].nodeName + ' tag BUT it is empty!');
} else {
console.log('Yes, this has a ' + all[i].nodeName + ' tag and it is NOT empty!');
}
} else {
console.log('Sorry ' + all[i].nodeName + ' tag, doesn\'t have an alt tag!');
}
}
});
}
You can do it in one loop. Check for the value of alt after checking if the attribute exists.
Note that alt is a standard property of the img tag but not div. In the example I used .getAttribute for the the non-standard property. If I used img tags then .getAttribute could be replaced with .alt since that's a standard property of the tag. see comments.
function altChecker() {
var out = [];
var doc = document;
var all = doc.getElementsByTagName("div");
for (var i = 0, max = all.length; i < max; i++) {
var id = all[i].id;
if (all[i].hasAttribute('alt')) {
out.push(id + ' has alt');
var value = all[i].getAttribute('alt');
if (value != "") {
out.push(id + ' alt="' + value + '"');
} else {
out.push(id + ' alt is empty');
}
} else {
out.push(id + ' does not have alt');
}
}
doc.getElementById('output').innerHTML = out.join("\n");
}
altChecker();
<div id='a' alt='foo'>-</div>
<div id='b' alt='bar'>-</div>
<div id='c' alt=''>-</div>
<div id='d'>-</div>
<pre id='output'></pre>
You're missing your .length property in the 2nd if:
max2 = all
Should be max2 = all.length
If you intended to loop though the all collection twice, you missed the length property on all in the second loop, and you need to start the j variable from 0.
for (var j = i, max2 = all; j < max2; j++) {
should be:
for (var j = 0, max2 = all.length; j < max2; j++) {
The two loops are completely independent and just iterate over the all collection; you write them in exactly the same way.
Mistakes like that are why I usually use functional idioms for looping:
$.each(all, function(idx, each){...});

load an image in a particular element using javascript

I have a place for the main photo (id = "main") and other photos in the table (id = "pic+1(2,3,4,5,6)"). I would like to click on a photo with id = "pic n" and to load it in the element with id "main". How to realize this?
Also I have an error
Uncaught TypeError: Cannot set property 'onclick' of null.
Here is my code:
<img id="main" src="">
galery(dir){
...
...
function createPreview() {
var f = document.createElement("table");
var row = f.insertRow();
for(var j = 0; j < count ; j++) {
var cell = row.insertCell(j);
var img = new Image();
img.src = dir + '/' + j + ".jpg";
img.width = "100";
img.id = 'pic' + j;
cell.appendChild(img);
}
document.body.appendChild(f);
}
document.getElementById(this.pic).onclick = function() {
document.getElementById('main').src = this.src;
}
...
}
Although your code has many errors and misunderstandings on how js works here is some simple code that solves this issue
//fake an image directory
var count = 3;
var dir = 'http://lorempixel.com/300/300/abstract/'
//setup a table
var f = document.createElement("table");
var row = f.insertRow();
for (var j = 0; j < count; j++) {
var cell = row.insertCell(j);
imagepath = dir + j;
cell.innerHTML = '<img src="' + imagepath + '" width="100" onclick="showmain(' + j + ')">';
}
document.body.appendChild(f);
//change imagesrc in main tag
function showmain(image) {
document.getElementById('main').src = dir + image;
}
This is the most basic (noob) thing you do with javascript.
I strongly suggest you read some more tutorials before coming back with such basic questions.
Here is a Plunker.
No onload handler, so the script is at the end of the page.
You have a lot of errors in your code:
1) You define var f inside the function, so its scope is inside the function. But then you try to get it outside the function with document.body.appendChild(f); which doesn't work. you should move document.body.appendChild(f); inside the function.
2) Then you get Uncaught TypeError: Cannot set property 'onclick' of null. because document.getElementById(this.pic) returns null. this.pic returns no id.
3) close your img tag.
4) You have 2 extra }
And I am sure there are more if you show us all your code.

id for each element showing undefined or 0 not being assigning different id's

I'm trying to assign a id to each link in my list like this,
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
$('#citations').append('<li><a href="' + link + '" id="num" + j>' +
json[j].title + '</a></li>');
alert($('a').attr('id'));
}
it keeps giving me undefined or 0? Should I use $.each outside of the for loop instead?
I was trying to use the for loop for two purposes but maybe that's not such a great idea?
*EDIT***
If I put my for loop inside of a function like,
// Loop function for each section
var loopSection = function(start, stop) {
// Http setup for all links
var linkBase = "http://www.sciencebase.gov/catalog/item/";
// Link for citation information
var link = "";
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
var $anchor = $("<a>", {
href: link,
id: "id" + j,
text: json[j].title
})
// .parent() will get the <li> that was just created and append to the first citation
element
$anchor.appendTo("<li>").parent().appendTo("#citations");
}
}
I'm not able to access the id from outside of the function
$('#citations').on('click', function (e) {
e.preventDefault();
var print = ($(this).attr('id'));
alert(print);
});
This form is much cleaner:
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
$("<a>", {
href: link,
id:'num' + j,
text: json[j].title
}).appendTo("<li>")
.parent() // get the <li> we just made
.appendTo("#citations");
}
If you want a reference to the anchor tag you created, do this:
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
var $anchor = $("<a>", {
href: link,
id:'num' + j,
text: json[j].title
});
$anchor.appendTo("<li>").parent().appendTo("#citations");
}
You have a syntax error in your code (id="num" + j..)
However,You should do this by the code (avoiding syntax error and giving a better performance)
for (var j = start; j < stop; j++)
{
var link = linkBase + json[j].relatedItemId;
$('#citations').append($(document.createElement('li'))
.append($(document.createElement('a'))
.attr('href', link)
.attr('id', 'num' + j)
.html(json[j].title)));
}
Agree with the answer from Schmiddty but, for the sake of completeness
for (var j = 0; j < 10; j++) {
var link = "someLink.htm";
$('#citations').append('<li>'+ 'click here' + '</li>');
alert($('#citations a:last').attr('id'));
}
I've only changed your variable to make it work on its own on this fiddle as a demo

Categories