If I have this line and I'm wondering if there's better way to do it.
var TheID = $(this).parent().parent().parent().parent().parent().attr('id');
Note that the div for which I'm looking for the ID has class "MyClass", if that can help.
Thanks.
you can also try closest for get attribute like this :
$(this).closest('div.Myclass').attr('id');
or second way is
$(this).parents('div.Myclass').attr('id')
see here : http://jsfiddle.net/sKqBL/10/
Get all the .parents(), and use .eq()...
$(this).parents().eq(5).attr('id');
...or the :eq() selector...
$(this).parents(':eq(5)').attr('id');
...or make a function...
function up(el, n) {
while(n-- && (el = el.parentNode)) ;
return el;
}
...and use it like this...
up(this, 5).id
What is your definition of better?
//POJS, fastest
var TheID = this.parentNode.parentNode.parentNode.parentNode.parentNode.id;
//jQuery, terse
var TheID = $(this).closest(".MyClass").prop("id");
var TheID = $('.MyClass').attr('id');
or
var TheID = $('#MyClass').attr('id');
is this what you mean? that will get the ID of .MyClass
you can use .parents
var TheID = $(this).parents(".MyClass").attr('id');
Is the id that you are trying to retrieve dynamically generated and so therefore you don't know what it is?
If so, consider assigning a unique CSS class name to the great-great-great grandparent. Then you should be able to do something like this:
$(".MyGreatGreatGreatGrandparentCssClass").attr("id");
Of course, if you do this you may not need the great-great-great grandparent's id.
Related
I have a bunch of divs with matching ids (#idA_1 and #idB_1, #idA_2 and #idB_2, etc). In jquery I wanted to assign click functions, so that when I click an #idA it will show and hide an #idB.
Basically I want to make this:
$(".idA_x").click(function(){
$("idB_x").toggleClass("hide")
});
X would be a variable to make #idA and #idB match. I could write each individually, but that would take too much code, is there a way to make the number in the id into a variable?
Sure, you can do:
var num = 13;
addButtonListener(num);
function addButtonListener(num){
$("#idA_"+num).click(function(){
$("#idB_"+num).toggleClass("hide")
});
}
Try JQuery solution :
var x = 1;
$(".idA_" + x ).click(function(){
$(".idB_" + x ).toggleClass("hide")
});
Hope this helps.
There are many ways to achieve that, but what you probably want is to create a shared CSS class, e.g. .ids, and bind the event listener to that one:
$('.ids').click(function () {
//...
});
Then you can handle your logic in a cleaner way within the function body.
In order to make it dynamic, and not have to repeat the code for each one of your numbers, I suggest doing as follows:
First, add a class to all the div's you want to be clickable .clickable, and then use the id of the clicked event, replacing A with B in order to select the element you what to toggle the class:
$(".clickable").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
Or, you can also select all divs and use the contains wildcard:
$("div[id*='idA_']").click(function(){
var id = $(this).attr('id');
$("#" + id.replace('A', 'B')).toggleClass("hide");
});
This solution won't have the need to add a class to all clickable divs.
You can use attribute selector begins with to target the id's you want that have corresponding elements.
https://api.jquery.com/attribute-starts-with-selector/
Then get the value after the understore using split on the id and applying Array.pop() to remove the 1st part of the array.
http://jsfiddle.net/up9h0903/
$("[id^='idA_']").click(function () {
var num = this.id.split("_").pop();
$("#idB_" + num).toggleClass("hide")
});
Using regex would be your other option to strip the number from the id.
http://jsfiddle.net/up9h0903/1/
$("[id^='idA_']").click(function () {
var num = this.id.match(/\d+/g);
$("#idB_" + num).toggleClass("hide")
});
Do someone know what is the best way to replace some string inside a onclick attribute ?
I need to get the current value and replace some text inside parameters.
Exemple, I have this link:
My link
And I want this:
My link
In other words, I want something like this:
$('a').attr('onclick', $(this).attr('onclick').replace('1', '2'));
And I know I can do this, but I need something dynamic retreiving the values of current element:
$("a").attr('onClick', "myfunction('parameter2a','parameter2b')");
Finally it working when I made a simple demo: http://jsfiddle.net/GkWhh/4/
Thank you for your solutions !
$('a[onclick]').attr('onclick', function(i, v){
return v.replace(/1/g, '2');
});
http://jsfiddle.net/cj9j7/
If you need something more dynamic do not use onclick attributes, changing onclick attributes is hackish, you can use click method instead.
var param = 1;
$('a').click(function(){
// ...
if ('wildguess') {
param = 1;
} else {
param++;
}
})
sounds like a really bad idea but anyway - you can access the string value of the onlick attribute using something like that:
$('a').each(function() { this.attributes.onclick.nodeValue = this.attributes.onclick.nodeValue.replace('1', '2'); })
You can do this: http://jsfiddle.net/SJP7k/
var atr = $('a').attr('onclick');
var str = atr.split('1');
var natr = str.join('2');
$('a').attr('onclick',natr);
I want to get the content of multiple Spans. Here is my code:
http://jsfiddle.net/4XumV/
It's supposed to give me "111, 222, 333, 444". It gives me "undefined" instead.
What's wrong with my code?
Well, you weren't actually getting the innerHTML property, you were getting an undefined html property. Change it to innerHTML and it will work.
http://jsfiddle.net/4XumV/1/
This should work:
$(function()
{
var allLatestNews = $("#main").find('span');
$.each(allLatestNews, function(i,val){
alert($(val).text());
});
});
I was wondering WHY your code wasn't working and JQuery does return an array of elements from the selector, this could have also worked:
for(var i = 0; i < allLatestNews.length; i++)
{
alert($(allLatestNews[i]).text());
}
First wrap the element as a JQuery object and then querying text() not html, which is accessed by a function not a property.
Your updated fiddle: http://jsfiddle.net/4XumV/9/
You seem to be confusing jquery's html with innerHTML.
You can either use innerHTML:
http://jsfiddle.net/4XumV/3/
alert(allLatestNews[i].innerHTML);
or jquery's html:
http://jsfiddle.net/4XumV/5/
alert(allLatestNews.eq(i).html());
Try this it should work
allLatestNews.each(function()
{
alert($(this).html());
});
var $elms = $('#main').find('span');
$elms.each(function(){ alert($(this).text()); });
http://jsfiddle.net/4XumV/2/
This is working
var allLatestNews = $("#main").find('span');
$.each(allLatestNews ,function( index , value){
console.log($(value).html());
});
instead of console.log($(value).html()); you can write alert($(value).html());
The property of a DOM element to return the inner HTML is named innerHTML not html
allLatestNews[i].innerHTML
Or using jQuery
$(allLatestNews[i]).html()
Updated JS Fiddle
you can also use this
var allLatestNews = $(this).find("#main span");
for(var i = 0; i < allLatestNews.length; i++)
{
alert(allLatestNews[i].innerHTML);
}
Is there a way to me do this?
<img id="example" src="anything.jpg" title="something" class="abc" />
$('.abc').each(function(){
//test if this result is something
if( $(this)...(???)...('[src^=anything]')) == 'anything.jpg'){
}
//another Jquery selector test for this one
if( $(this)...(???)...('#example').size() > 0){
}
});
This is just an example, what I need is pretty more complex.. But I would like to know if there is a way to make other jQuery selector test in the result of a first selector.. since "find" will find the children of $(this).. and .parent() get alot of brothers..
See what I mean?
Do you have any idea?
So sorry.. let me try again..
$('div').each();
get all "div", right?
But now in that function I need to make another "test" check if div class is "red" or "blue"..
See?
I need to test something else of the result based in Jquery selector..
I know I could do:
class = $(this).attr('class'); and then if(class=="blue"){} .. But I would like to do $('this[class=blue]').size()>0){}
The jQuery is() filter operates on a found set to detect if something is true or not.
The jQuery filter() method will further pare down a found set based on criteria.
var allDivs = $('div');
var greenOnes = allDivs.filter('.green');
var redOnes = allDivs.filter('.red' );
I think you need the is method:
$('.abc').each(function() {
$(this).is('[src^=anything]')
});
This is fairly simple though, but I can't really tell what you are trying to do by the description. Maybe this is enough to get you started though.
You can use the filter and is methods to filter/search within a jQuery object.
if( $(this).is('[src^="anything"]') ) {
}
elseif( $("#example").size() > 0) {
}
You could put $("#example") in a variable outside of the loop and then reference it inside the loop as well.
if(this.src.indexOf("anything") === 0) {
// source starts with 'anything'
}
if($("#example").length) {
// since there can be only one #example
// in a *valid* document
}
Based on your edit:
if($(this).hasClass("blue")) {
...
}
?
Why is line 10 returning null?
http://pastie.org/720484
it works with line 40
You do not seem to have a proper grasp of the siblings() operator. You also were not utilizing jQuery's val() function and were missing periods on some of your class names. To locate the address1 class you would need to do the following:
var $checkbox = jQuery(this);
$checkbox.parent().siblings('.formField').find('.address1');
Also, you would want the alert to be
alert($checkbox.parent().siblings('.formField').find('.address1').val());
to alert the value of the input box.
FIXED AND OPTIMIZED VERSION:
function update_address(eventObject) {
var $checkbox = jQuery(this);
var $siblings = $checkbox.parent().siblings('.formField');
if ($checkbox.attr('checked')) {
$siblings.find('.address1').val($('.hidden_address1').val());
$siblings.find('.address2').val($('.hidden_address2').val());
$siblings.find('.city').val($('.hidden_city').val());
$siblings.find('.state').val($('.hidden_state').val());
$siblings.find('.zip').val($('.hidden_zip').val());
$siblings.find('.province').val($('.hidden_province').val());
$siblings.find('.country').val($('.hidden_country').val());
} else {
$siblings.find('.address1').val('');
$siblings.find('.address2').val('');
$siblings.find('.city').val('');
$siblings.find('.state').val('');
$siblings.find('.zip').val('');
$siblings.find('.province').val('');
$siblings.find('.country').val('');
}
}
try fetching the input:text's .val() instead
On line 9, shouldn't it be var checkbox = $(this); instead? I've not seen the jQuery() function used like that.
Because <input class="address1"/> is not a sibling of <input id="parent_sameAsBefore"/>. I think you want:
checkbox.parent().parent().find('.address1');
Why not just go with finding the form fields using absolute path?
Unless your DOM is very convoluted (and you need relative paths), I would prefer this approach myself.
Also use .val() to get and set values.
function update_address(eventObject) {
if($(this).attr('checked')) {
$('#parent_address1').val($('hidden_address1').val());
$('#parent_address2').val($('hidden_address2').val());
$('#parent_city').val($('hidden_city').val());
$('#parent_state').val($('hidden_state').val());
$('#parent_zip').val($('hidden_zip').val());
$('#parent_province').val($('hidden_province').val());
$('#parent_country').val($('hidden_country').val());
}
else {
$('#parent_address1').val("");
$('#parent_address2').val("");
$('#parent_city').val("");
$('#parent_state').val("");
$('#parent_zip').val("");
$('#parent_province').val("");
$('#parent_country').val("");
}
}
Note, seems to be a bug in the original code in line 15:
checkbox.siblings('.tate').value = $('hidden_state').value;
Should be:
checkbox.siblings('.state').value = $('hidden_state').value;
alert(checkbox.siblings('.address1').html() ); // This should be
alert(checkbox.parent().siblings('.address1').html() );
//Checkbox does not have siblings
Line 10