get a value with a jquery for loop - javascript

I have several item in a databse, I'm displaying a link with in the href the id of each item.
So I want to get the id from a href which is in a PHP while loop. So I did a for loop to do it but it seems to only get the first href attr.
for (var i = 0; i < check; i++)
{
var id = $(".id").attr('href');
console.log(id);
}
Check is equal to the number of columns in the database depends of a special id. In this case check = 3
The link is: echo '<a id="dislike" class="btn-primary btn pull-right id" href="'.$items['id'].'">Dislike</a>';
Any idea of why it doesn't work ?
I got them all!
But how can I make them go out of the function ?
function checkingfetchresult(userid){
$.post("ajax/checkingfetchresult.php", { userid: userid },
function(check){
$(".id").each(function(){
var id = $(this).attr('href');
});
});
}

You are selecting the same elements on each iteration and then getting the attribute of the first element in the set. Instead of looping like that, you should use each:
$(".id").each(function(){
var id = $(this).attr('href');
console.log(id);
});

You're getting the first element every time, and logging its href. You can't expect a loop to behave differently if it's doing the same thing every time?
If you want to get all the href attributes for all the .id elements, use map:
$('.id').map(function () { return $(this).attr("href") });
It will return an array, where each element is the href of the corresponding .id element.

$(".id") returns an array-like object, containing all of the matching elements. what you actually want to do is this:
var idArray = $(".id");
for (var i = 0; i < check; i++) {
var id = $(idArray[i]).attr('href');
console.log(id);
}

Related

Get JavaScript Object

I am working client side on a web page that I am unable to edit.
I want to use JS to click on a particular button, but it does not have a unique identifier.
I do know the class and I do know a (unique) string in the innerHTML that I can match with, so I am iterating through the (varying number) of buttons with a while loop looking for the string:
var theResult = '';
var buttonNum = 0;
var searchString = '720p';
while (theResult.indexOf(searchString) == -1
{
theResult = eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum + \"].innerHTML\");
buttonNum++;
}
Now I should know the correct position in the array of buttons (buttonNum-1, I think), but how do I reference this? I have tried:
eval(\"document.getElementsByClassName('streamButton')[\" + buttonNum-1 + \"].click()")
and variation on the position of ()'s in the eval, but I can't get it to work.
You could try something like:
var searchStr = '720p',
// Grab all buttons that have the class 'streambutton'.
buttons = Array.prototype.slice.call(document.querySelectorAll('button.streamButton')),
// Filter all the buttons and select the first one that has the sreachStr in its innerHTML.
buttonToClick = buttons.filter(function( button ) {
return button.innerHTML.indexOf(searchStr) !== -1;
})[0];
You don't need the eval, but you can check all the buttons one by one and just click the button immediately when you find it so you don't have to find it again.
It is not as elegant as what #Shilly suggested, but probably more easily understood if you are new to javascript.
var searchString = '720p';
var buttons = document.getElementsByClassName("streamButton"); // find all streamButtons
if(buttons)
{
// Search all streamButtons until you find the right one
for(var i = 0; i < buttons.length; i++)
{
var button = buttons[i];
var buttonInnerHtml = button.innerHTML;
if (buttonInnerHtml.indexOf(searchString) != -1) {
button.click();
break;
}
}
}
function allOtherClick() {
console.log("Wrong button clicked");
}
function correctButtonClick() {
console.log("Right button clicked");
}
<button class='streamButton' onclick='allOtherClick()'>10</button>
<button class='streamButton' onclick='allOtherClick()'>30</button>
<button class='streamButton' onclick='correctButtonClick()'>720p</button>
<button class='streamButton' onclick='allOtherClick()'>abcd</button>
I would stay clear of eval here, what if the text on the button is some malicious javaScript?
Can you use jQuery? if so, check out contains. You can use it like so:
$(".streamButton:contains('720p')")

Trying to remove element based on type of attribute

I am trying to remove an element based on type of attribute. It isn't working for some reason.
The element in question is this:
<p style="width:250px;font-size:11px;text-align:left;margin-left:1.2ex;margin-top:0px;margin-bottom:0px;line-height:1.15em;">– in Europe<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green & dark grey</span>)<br>
– in the European Union<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green</span>)</p>
I am trying to remove it this way - item is a container element.
$(item).find("p").filter("[style]").remove();
There are no other <p> tags with the attribute style, however this doesn't appear to remove it.
Other code, like this, works fine:
$(item).find(".reference").remove();
How do I remove all p tags with the style attribute from the item element?
This is how item is created:
$.get(link, function(response) {
var elements = $.parseHTML(response);
var wiki = $(elements).find('#mw-content-text').find("p");
//var ps = [];
var arrayLength = wiki.length;
for (var i = 0; i < arrayLength; i++) {
if (wiki[i].innerHTML === "") {
break;
}
var item = wiki[i];
The link variable is a link to wikipedia.
Maybe try this:
$.each(item.children('p'), function(index) {
if ($(this).attr('style')) {
$(this).remove();
}
});
item refers to p element itself. you don't have to find p in item:
$(item).filter("[style]").remove();
after re-looking over your question ,
$(item).find("p").filter("[style]").remove();
is perfectly valid , instead of trying to come up with alternative ways to write it , find out what is wrong with item, because it is not what you think it is if above code is not working

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

Get every UL element's ID for a specific class

Goal: Get a specific HTML element ul's id value from a ul class called SBUpdater
Purpose: My program contains several server url's and parses specific information that I need from each server url. Each id of a ul contains the value of a server url. I need to take this ID value so i can update that specific ul tag and update the content on the screen (without refreshing the page).
In a php file I have the following:
Example Code:
<ul id="http://server1.com" class="SBUPdater">
<li> ... </li>
</ul>
<ul id="http://server2.com" class="SBUPdater">
<li> ... </li>
</ul>
All I need is a method of getting this id value from the ul tags.
Known:
Tag = ul
Class = SBUpdater
ID = ?
What I would like is to retrieve every ul's id value, take all ul id's, perform a function with them, and then repeat the process every 10 seconds.
You can use .map(), though your IDs are invalid, like this:
var idArray = $(".SBUPdater").map(function() { return this.id; }).get();
I'd use a data attribute though, like this:
<ul data-url="http://server1.com" class="SBUPdater">
And script like this:
var urlArray = $(".SBUPdater").map(function() { return $(this).attr("data-url"); }).get();
Or, if you're on jQuery 1.4.3+
var urlArray = $(".SBUPdater").map(function() { return $(this).data("url"); }).get();
With prototype library you would do this:
$$('.SBUPdater').each(function(){
new Ajax.PeriodicalUpdater(this, this.getAttribute('data-url'), {
frequency: 10 // every 10 seconds
});
});
Each ul element would use the data-url (not id) attribute to hold the URL of your server script. That script would then return the new content of the appropriate ul element.
Thanks to Nick Craver for excellent suggestion
$('ul.SBUPdater').each(function(){
alert(this.id);
});
Hmm maybe something like this:
var urls = new Array();
var count = 0;
$('.SBUPdater').each(function() {
urls[count] = $('.SBUpdater').attr('id');
count++;
}
for(var i = 0; i < count; i++) {
//do something with urls[i];
}
It could even be inside of the each function.
setInterval( function(){
$('ul.SBUPdater').each(function(){
// use this.id
console.log(this.id);
})
}, 10000 );
this should do it..
In jQuery this would be as easy as:
var ids = $('.SBUPdater').map(function(el) {
return el.id;
});
console.log(ids); // ids contains an array of ids
To do something with those ids every 10 seconds you could setInterval:
window.setInterval(function() {
$.each(ids, function(id) {
console.log(id);
});
}, 10 * 1000);
EDIT:
function GetULs() {
var ULs = document.getElementsByTagName("UL");
var IDs = new Array();
for(var i = 0; i < ULs.length; i++) {
if(ULs[i].className == "SBUPdater") {
IDs.push(ULs[i].id);
}
}
return IDs;
}
This function will return an array of all of the element IDs that you are looking for. You can then use that array for whatever you need.

How to get all elements inside "div" that starts with a known text

I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS

Categories