Suppose the following HTML:
<li class="fooli">
<a class="foo" href="javascript:foo(this);">anchor</a>
</li>
<li class="fooli">
<a class="foo" href="javascript:foo(this);">anchor</a>
</li>
and the following Javascript (using jquery 1.3.2):
function foo(anchor) {
alert($(anchor).attr('href'));
}
My goal is to be able to hide the li that is clicked on, but I can't assign them unique ids. Thus, I want to do it positionally (i.e. identify the particular anchor clicked on) by something like $(anchor).parent().hide().
However, the alert above returns "undefined", so it's not obvious to me that I even have the right jquery object.
How do I figure out what object $(anchor) is? In particular, how do I see what attributes it has, what class it has, what HTML element it is, etc?
Can't you do this:
$(function() {
$("a.foo").click(function() {
$(this).parent().hide();
return false;
});
});
with:
<li class="fooli"><a class="foo" href="#">anchor</a></li>
<li class="fooli"><a class="foo" href="#">anchor</a></li>
$(...) in jQuery is never a single HTML element; it's always a list of them.
You can use .get() to convert to a regular Javascript list or, better, use .each():
$(anchor).each(function() { alert(this) });
This will give you something like [object HTMLAElement]. You'd have to use for/in to examine it entirely, but .tagName and .innerHTML are probably good enough to figure out where you are.
I also like to use $(...).css('outline', '1px solid lime') to find elements. It makes them hard to miss and easy to pinpoint with Firebug.
Addendum: I definitely agree with the above answer about separating your Javascript from your HTML. Don't inline JS.
Related
I have a div filled with spans that don't have an id on them, and need to be able to determine if one of those spans is marked(highlighted). My approach at first was the following:
function isSelected(element){
var selectedElement = window.getSelection().anchorNode.parentNode;
if($(selectedElement).index() === $(element).index()){
// It's selected
}
}
But this solution doesn't consider cases where other elements from another div are selected that have the same index.
I tried comparing the element objects like this:
$(selectedElement).get() == $(element).get()
and like this:
$(selectedElement) == $(element)
but the comparison was always returning false.
How do I determine if they're the same without giving every span an id?
Solution:
if(selectedElement.isEqualNode(element){
}
if(selectedElement.isEqualNode(element){
}
Try to use this code:
if ($('div span .highlighted')){
alert ('span is highlighted');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<span class="highlighted"></span>
<span class="normal"></span>
</div>
</div>
This thread is discussing a topic related to your situation Object comparison in JavaScript
Maybe one of their suggestions helps you. Unfortunately Javascript does not provide anything like .ReferenceEquals() like for example C# does.
I would like to know if there is an easier way to check if an element has an ancestor with a particular class.
Consider the following HTML code:
<ul id="uniqueID" class="parentClass">
<li class="subclassA">
<div class="subclassB">
<nobr>
MyText
</nobr>
</div>
</li>
<li class="subclassA"> ... </li>
<li class="subclassA"> ... </li>
<li class="subclassA"> ... </li>
</ul>
<div>other elements in this page which I want to select</div>
Right now, I can select the element MyText by using a jQuery selector checking the href for a particular format. What I can then do is do .parent() a known number of times (4) and then check the class attribute of that particular element that I've now moved to. While this is working just fine, I am curious if there is a better way to do it, perhaps one that lets me be a bit more dynamic?
PS. There are a lot of elements that I'm selecting that'll fit this $('[href *= index.php]') format, so I want to keep those but remove the ones that fall under the categorization where they are a descendant of a member of class listclass. Currently I'm just selecting all of the elements with the selector above, then using an if statement to check through and see if it fits this condition. Again, if there is a more efficient way to do this (perhaps select these certain elements in the first place?) I would love to hear about it.
Current code:
$('[href *= "index.php"]').each(function(){
if ($(this).parent().parent().parent().parent().attr('class') != 'parentClass'){
//do things
}
});
To generalise you can use
.closest(".parentClass")
You can use closest and is:
$('[href*="index.php"]').each(function(){
if ($(this).closest('ul').is('.parentClass')) {
//do things''
}
});
if($(this).parents("ul.parentClass").length == 0){
//do something
}
I have a page with many dynamically creted div's as seen below:
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
<div class="open"></div>
I'm looking for a way to get get a position of an element (eg. If the element is the first instance of, assign id="1" if element is the second instance of, assign id="2".
I'm currently using the following jquery, but am stuck, as Im not sure where to go from here.
$(document).ready(function () {
var numDialogs = $('.open').length;
});
Any suggestions?
Just use:
$('div.open').prop('id', function(i){
return 'openElement' + (i + 1);
});
JS Fiddle demo.
I've deliberately added a prefix string because while numerical ids are valid under HTML5, they remain invalid under HTML4, and are difficult to select using CSS selectors.
References:
prop().
Mark, you can target the element and then add an attribute like so:
$('.open').attr('id', numDialogs);
This will give it all 4's in this case, but I'll leave you to wrestle with the actual logic to implement the right numbers. Good luck.
Jquery:
//Jquery-JS search for actors and directors
//Hide extra Actors
$(".actor ul li").not($(".actor ul li").slice(0,11)).hide();
//
function find_and_unhide (keyword,container) {
$(container+':contains("'+keyword+'")').show();
}
find_and_unhide("fra",".actor ul li");
Html:
<div class="option-combo actor">
<h4>Actor →</h4>
<ul class="filter option-set" data-filter-group="actor">
<li>Any</li>
<li>Sandro</li>
<li>Barbara</li>
<li>Ku</li>
<li>Cool</li>
<li>Aid</li>
<li>Leo</li>
<li>John</li>
<li>Kvara</li>
<li>Kuku</li>
<li>Bubu</li>
<li style="display: none;">Fra</li>
</ul>
</div>
Find and Unhide function doesn't work.
I'm also wondering if I should use data-filter-value instead of contains to select correct li. But which one will be faster?
Also How do i implement fuzzy matching?
I would do something like this to fix your find and unhide function:
function find_and_unhide (keyword,container) {
$(container).find('[data-filter-value="' + keyword + '"]').show();
}
I definitely think searching on the data attribute would be both faster and be more extensible in the long term, however, especially since you narrow down the DOM that needs to be searched I imagine the performance difference will be negligible either way. I personally think its cleaner to use the data attribute.
Don't know much about fuzzy matching, but maybe this question will give you a starting point : Getting the closest string match
Let's face this situation:
<ul>
<li>data</li>
<li class="selector">data2</li>
<li class="selector2">data3</li>
</ul>
What i'm trying to do is match lis that either have selector class or have class attribute undefined, something like this:
jQuery(function($) {
$('.selector2').prevAll('li.selector OR li[class==""]');
});
So if I'm running prevAll() on the .selector2, it should return 2 list items. If i run it on .selector, it should return the first list item.
So is there a way to replace that OR ... ?
PS: xpath may work for me too as i'm developing for modern browsers
jQuery(function($) {
$('.selector2').prevAll('li.selector, li:not([class])');
});
DEMO
Adding in important comment from #pimvdb
This is correct, but be careful - something like
.addClass("foo").removeClass("foo") leaves the class attribute
behind, although you (might) expect it to be in it's initial state. So
it's not quite the same as [class=''].
What i'm trying to do is match lis that either have "selector" class
or have class attribute undefined
This XPath expression is equivalent to the pseudo-code in the question:
/ul/li[#class='selector2']/preceding-sibling::li[#class='selector' or not(#class)]
However, a literal translation of the quoted requirement is:
/ul/li[#class='selector' or not(#class)]