Get every UL element's ID for a specific class - javascript

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.

Related

Javascript - Pull attribute into array/delete items based on attribute

I want to pull into an array the classes of all of the <img> in a particular <div> and then use those classes to delete the first <img> that shares that class in a different <div>.
So far, I have this that calls the original array:
var class = $('.frame div img').each(function() {
return $(this).class;
}).get();
class.forEach(function(entry) {
console.log(entry);
});
The log outputs a list of the <img></img> lines.
After that, I get stuck.
//Iterate through array and delete first <img> in #grid that has the same class, limit one per iteration.
// var img_class = $.each(class, function(key, value) {
// console.log(value);
// return $(this).attr('class');
// });
$('#grid img').each(function(){
if($(this).attr('class') == img_class){
$(this).remove();
}
});
The goals are:
Getting an array of classes into the img_class variable
Delete only the first <img> as it iterates through each class in the array
Thanks!
I am not sure if I understood it right but would something like this be of any help?
var firstIDs = "";
$('.frame div img').each(function() {
firstIDs += $(this).attr('id') + ",";
});
var SplitIDs = firstIDs.split(",");
$('#grid img').each(function(){
for(var i = 0; i < SplitIDs.length; i++) {
if($(this).attr('id') == SplitIDs[i]){
$("#grid img #"+$(this).attr('id')+":first").remove();
}
}
});
I would suggest to use some other attribute than class, eg. 'data-type'.
With the collected attribute values (e.g. 'types' array) do:
var $grid = $('#grid');
// iterate over collected types
types.forEach(function(type)) {
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
}
You could also do all in one rush:
// iterate over source <img> set
$('.frame div img').each(function() {
// get current images type-attrib
var type = $(this).attr('data-type');
// find within $grid the first <img> with data-type == type and remove it from DOM
$grid.find('img[data-type="' + type + '"]:eq(0)').remove();
});
Try
$(function() {
var classes = $.map($(".frame div img"), function(v, k) {
return [$(v).attr("class")];
});
var d = [];
console.log($("#grid img").length);
$.each($("#grid img"), function(k, v) {
if ( classes.hasOwnProperty($(v).attr("class")) ) {
d.push(v); $("body").find($(d.slice(0, 1))).remove();
};
});
console.log($("#grid img").length);
});
jsfiddle http://jsfiddle.net/guest271314/yv95C/

Get Html.ActionLink parameters from li element with query

I have this unordered list:
<ul class="list">
<li class="navItem">#Html.ActionLink("Home", "Index", "Home")</li>
<li class="navItem">#Html.ActionLink("Contact", "ContactForm", "Contact")</li>
</ul>
and in my script i want to select the li element by his action and controller name, that i can retrieve data like width and position from the specific li element.
my Function looks like this, but i don't know how the selector has to look like.
function currentItem() {
//Here i get the current view and controller name
var actionName = '#ViewContext.RouteData.Values["Action"].ToString()';
var controllerName = '#ViewContext.RouteData.Values["Controller"].ToString()';
// something like that, putting the link together?
var $currentItem = $('a[href="' + viewController + controllerName + '"]');
// or find all elements by class name an than do something like
var myArray = $('.navItem');
if (myArray[0].Controller == controllerName ||myArray[0].Action == actionName) {
$currentItem = myArray[0];
}
return $currentItem;
}
Thanks for helping.
Franhu
First of all lets consider what HTML we will be working with. A Html.ActionLink will convert into an a tag, so your HTML will look something like this:
<li class="navItem">Home</li>
With that in mind we can iterate the li elements, check their inner a element and match on the href attribute.
So something like this should work:
function currentItem() {
var actionName = '#ViewContext.RouteData.Values["Action"].ToString()';
var controllerName = '#ViewContext.RouteData.Values["Controller"].ToString()';
var listItems = $('.navItem');
for(var i = 0; i < listItems.length; i++){
var item = $(listItems[i]);
var a = item.find("a");
if(a.attr["href"].indexOf(controllerName + "/" + actionName) != -1){
return item;
}
}
}
Note that this will return the matching li element. If you want the matching a element then use return a; instead.

Link getElementsByTagName calls to traverse DOM for items you need

I have a page with a bunch of paragraphs. Each paragraph has an href that i want. However I dont want ALL the hrefs on the page, just the ones in the body ->p ->href.
How can I do this in javascript?
I want to do something like this, but it is wrong:
var myList = document.body.getElementsByTagName("p.href");
Note: I don't want to have to iterate over all p elements and extract the href, I just want to limit the scope of the hrefs.
sample input:
<p> <a href....></a></p>
In newer browsers :
document.querySelectorAll('p a[href="someLink"]')
or
var p = document.getElementsByTagName('p'),
arr = [];
for (var j=p.length; j--;) {
var a = p[j].getElementsByTagName('a'),
for (var i=a.length; i--;) {
arr.push( a[i].href );
}
}
Assuming you have links (<a> tags inside the <p> elements)...
You can do it with jquery like this:
var links = $('p a');
or like this if you want only direct children (not further descendants):
var links = $('p > a');
Or with pure javascript you'd have to loop through:
var paragraphs = document.body.getElementsByTagName("p");
for (var i=0;i<paragraphs .length;i++)
{
var links = paragraphs[i].getElementsByTagName("a");
// This is only the links in this paragraph, so you would need to add to a global list if you want to keep track of all of them in one place
}
If you want to get the href attribute from a link element, you can do it like this:
var link0href = links[0].href;
Well as #j08691 stated if your p elements have a href attribute they are invalid.
The following will get the href of an item where 0 is the index of an item
document.body.getElementsByTagName("p")[0].href

get a value with a jquery for loop

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);
}

Take <span> class and put in <a> attribute jquery

I have html like this.
<span class="gallery-open-item year-icon-Yes 2010">
<a href="/year/none">
</a>
</span>
I need to check using jQuery if span.gallery-open-item has year-icon-Yes class, and if so take the next (for this example is 2010) class and place it in the href attribute like this:
<a href="/year/2010"/>
All this I need in jQuery or JavaScript.
I have done some experiments but I can't take 2010 to normal javascript variable.
Any ideas?
Sorry for my English.
Here's another approach. Tested, working.
$('.gallery-open-item.year-icon-Yes').each(function(){
that = this;
var classes = $(this).attr('class').split(' ');
$.each(classes, function(i, val) {
if (val.match(/^y-/gi)) {
$('a', that).attr('href', function(){
return this.href.replace('none', val.split('-')[1]);
});
}
});
});
Assumes this markup:
<span class="gallery-open-item year-icon-Yes y-2010">
<a href="/year/none/">
Test
</a>
</span>
How about this:
$('span.gallery-open-item.year-icon-Yes > a').each(function(i, elem) {
$.each($(elem).parent().attr('class').split(' '), function(j, klass) {
// NOTE: use /^y-([\d]*)$/ if years are prefixed with y-
if (year = klass.match(/^([\d]*)$/))
$(elem).attr('href', $(elem).attr('href').replace('none', year[1]));
});
});
This would iterate over every A tag beneath your SPAN tags and fetch the classes from each parent, search these for a number and replace the "next" part.
Update: Added comments for the case you switch to prefixed years.
Update 2: Now tested and working (using Prototype usually *sigh*).
Here's one way of doing it. First, we select the span tags that have both the classes gallery-open-item and year-icon-Yes. Then, for each of them we're going to get an array of classes that the span tag has. I loop over the class names, and check for the first one that is a number. Finally, modify the a tag inside the span to set the desired url.
$(document).ready(function() {
$('span.gallery-open-item.year-icon-Yes').each(function() {
var classNames = $(this).attr('class').split(' ');
for (var i = 0; i < classNames.length; i++)
{
if (!isNaN(classNames[i]))
{
var year = classNames[i];
$(this).find('a').attr('href', '/year/'+year);
break;
}
}
});
});
Edit: Based on the comments that class names should not start with a number, it's pretty easy to make this work for class names of the form y-xxxx:
$(document).ready(function() {
$('span.gallery-open-item.year-icon-Yes').each(function() {
var classNames = $(this).attr('class').split(' ');
for (var i = 0; i < classNames.length; i++) {
var year = classNames[i].substring(2);
if (!isNaN(year)) {
$(this).find('a').attr('href', '/year/' + year);
break;
}
}
});
});

Categories