I'm trying to get all the found elements within a <div>, but by default it stops when it found the first occurrence, but I want it to list every found element's id value.
So this doesn't work:
listy = $("DIV").find("SPAN").attr("id");
I've been experimenting with .get and .map, but I think they're not what I want..
listy = $("div").find("span").map(function(){
return this.id;
}).get();
Without find is even better:
listy = $("div span").map(function(){
return this.id;
}).get();
Live DEMO
If you want only <span> with id attribute defined, change the selector to:
$(div span[id]).map(...)
If you want all the ids as a string:
listy = $("div span").map(function(){
return this.id;
}).get().join('');
The parameter of join is the delimiter, e.g. .join('-') or .join(',') or without: .join('')
Maybe this way?
var ids = [];
$("div span").each(function() {
if (this.id) {
ids.push(this.id);
}
});
attr() method will always return first elements attribute only.
var listy = '';
$("div span").each(function(){
listy += this.id ;
});
jsBin demo
Or like:
var listy = []; // create array
$("div span[id]").each(function(){ // span with ID data
listy.push( this.id ); // push ID names into array
});
// Now use listy.join(); to see the list
// you can also do: listy+'' to transform it into string.
jsBIn demo 2
Related
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/
I have an array with buttons:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
If one of them is clicked I want to get their index-value in the array:
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf(this); //($(this)) doesn't work either!
});
This doesn't work.
I used the jQuery method .index() instead:
var y = $(this).index();
but I'd rather not because the order of the buttons in the html is not the same as in the array.
Thanks for your help!
Since your array has IDs with hashes, then you need to search for the ID with a hash, not the element itself. There are two solutions:
Make your button array reference objects instead of IDs
var buttonnumber = [$("#btn1"), $("#btn2"), $("#btn3"), $("#btn4"), $("#btn5")];
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf($(this));
});
or do the indexOf against the id of the object you are clicking:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf("#" + this.id);
});
You can also write that click selector as:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
$(buttonnumber.join()).click(function() {
var y = buttonnumber.indexOf("#" + this.id);
});
In modern browsers, you also no longer need jQuery for something like this:
var buttonnumber = ["#btn1", "#btn2", "#btn3", "#btn4", "#btn5"];
// cast nodelist that's returned from querySelectorAll to array
Array.prototype.slice.call(document.querySelectorAll(buttonNumber.join()))
.forEach(el => {
el.addEventListener("click", (event) => {
let y = buttonnumber.indexOf("#" + this.id);
});
})
buttonnumber.indexOf(this);
Supposed to be
buttonnumber.indexOf('#' + this.id);
this corresponds to the DOM element. Need to get the id of that element and get the index based of of it.
Get the clicked items ID attribute with $(this).attr('id') and get your index from the string...
$("#btn1, #btn2, #btn3, #btn4, #btn5").click(function() {
var y = buttonnumber.indexOf($(this).prop("id"));
});
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);
}
I was wondering how to obtain the text inside a given div, with also the input's values as text.
<div id="example">This is a <input type="text" value="right"/> test.</div>
If I just try to get text like this with jQuery :
$("#example").text();
The result would be This is a test. and I'd want : This is a right test.
The number of input would be unknow. As well as the order of the elements...
EDIT :
I finally resolved my own problem :
var finalText="";
$("#example").contents().filter(function() {
if(this.nodeType==3){ finalText =finalText+ this.nodeValue;}
else if(this.nodeName=="INPUT"){ finalText=finalText+this.value;}
return finalText
})
The living example
But #Jonathan Lonowski answer is more clear and simpler than mine !
Here is a quick plugin that will do this for you:
$(document).ready(function() {
$.fn.extend({
getContentText: function() {
var t = '';
this.contents().each(function(i,c) {
var method = $(c).is("input") ? "val" : "text";
t += $(c)[method]();
});
return t;
}
});
alert($("#example").getContentText());
});
Try it out here:
http://jsfiddle.net/wQpHM/
You might try cloning so you can replaceWith the inputs with their values. Then grab the text as you were:
var clone = $('#example').clone();
clone.find(':input').replaceWith(function () {
return $(this).val();
});
alert(clone.text());
You can loop though all children of the <div> and replace then with their values. Something like this:
$.fn.allText = function(){
var $this = this.clone();
$this.children().each(function(){
$(this, $this).replaceWith(this.value);
});
return $this.text();
};
alert($('#example').allText());
Demo: http://jsfiddle.net/4mGmH/
get html and strip html tags
$('#example')[0].innerHTML.replace(/(<([^>]+)>)/ig, '').replace(/(\s+)/g, ' ')
Using innerText
document.getElementbyId('example').innerText;
To get HTML tags:-
document.getElementbyId('example').innerHTML;
Refer this URL element.innerHTML
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.