.prevUntil not working as expected - javascript

what am I doing wrong in this code..
I should get the class name of the previous sibling using this code.. but I am getting undefined..where am I going wrong
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JprevUntil</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
$('.clickme').live('click',function(){
alert($(this).prevUntil('li.lick').className);
});
</script>
</head>
<body>
<div>
<p id="hello">Hello World</p>
<li class="lick">hello i am li</li>
heello i am a
<p class="clickme">click</p>
</div>
</body>
</html>

you can use siblings() and attr() method, prevUnti is not what you want:
Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.
$('.clickme').live('click',function(){
alert($(this).siblings('li').attr('class'));
});
className is a javascipt core element property and cannot be used with jQuery objects, if you want to use className you can try this:
$('.clickme').on('click',function() { // you can use on(). live() is deprecated
alert($(this).siblings('li')[0].className);
});

From the prevUntil api documentation
*Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.*
You are expecting the prevUntil to stop at the li.lick but it is not included.
You can see live in this jsfiddle

Do this way:-
Refer LIVE DEMO
HTML:
<div>
<li class="lick2">hello i am li 2</li>
<p id="hello">Hello World</p>
<li class="lick">hello i am li</li>
heello i am a
<p class="clickme">click</p>
<li class="lick1">hello i am li 2</li>
</div>​
JS:
$('.clickme').one('click',function(){
alert($(this).prevAll('li').attr('class'));
});​
OUTPUT:
lick

Look what the jQuery documentation says about this:
Get all preceding siblings of each element up to but not including the
element matched by the selector, DOM node, or jQuery object.
Your element is NOT included thats why you don't get what you want.
You could try the following:
$('.clickme').live('click',function(){
alert($(this).prevAll('li.lick').get(0).className);
});
UPDATE:
Seems like what you want to achieve (getting the closest preceding sibling) can be done with that code (code taken from here):
$('.clickme').live('click',function(){
alert($(this).prevAll('li.lick:first').attr('class'));
});
FIDDLE

It's because you get a JQuery wrapped object, try :
$('.clickme').live('click',function(){
alert($(this).prev('li.lick')[0].className);
});
If you inspect your code for
$(this).prevUntil('li.lick')
You have :
-->$(this).prevUntil('li.lick'): e.fn.e.init[1]
0: HTMLAnchorElement
context: HTMLParagraphElement
length: 1
prevObject: e.fn.e.init[1]
selector: ".prevUntil(li.lick)"
__proto__: Object[0]
Your HTMLAnchorElement is a DOM object, it's here that you can retrieve your className property.

Related

Select element in Jquery selector by class name and convert it back to Jquery object

I don't understand why when i looking for how to get an element in list of element selected by class name like in traditional JS, I've always seen complicated answers .
document.getElementsByClassName('anyclass')[1]
so, i have found out myself that i cant do that (may be its the wrong approach)
$('.anyclass')[1]
but i get a DOM element! so logically i tried
$('.anyclass')[1][0]
and it doesnt work 'TypeError: $(...)[0][0] is undefined'
Anyone can explain why ? thank you!
I think you need .eq(index)
var secondElement = $('.anyClass').eq(1); //jQuery object
var domElement = secondElement[0]; //DOM element
console.log(secondElement, domElement)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='anyClass'>1</div>
<div class='anyClass'>2</div>
var elm = document.createElement("div");
var jelm = $(elm); //convert to jQuery Element
var htmlElm = jelm[0]; //convert to HTML Element
The :first pseudo-class is equivalent to :eq( 0 ). It could also be written as :lt( 1 ). While this matches only a single element, :first-child can match more than one: One for each parent.
here
$('.anyclass:first)
Quick example:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$($(".t")[1]).css("background-color", "yellow");
});
</script>
</head>
<body>
<p class=t>This 1.</p>
<p class=t>This 2.</p>
<p class=t>This 3.</p>
</body>
</html>
'
$('.anyclass')[0].attr("src"); you can use like this .
after your comment:
$(".anyclass")[1] is a DOM element not a jquery object. Simply wrap it as jquery $($("td")[1]).width()

Trouble using .closest function

I'm trying to make a sidebar menu for a dashboard. I want to implement this with .closest as it will fit with my code right. Here is a simple example of what I'm trying to do: https://jsfiddle.net/eu8kjzh4/10/
Why isn't the closest span's (and the only span in this case) text being replaced with a '-'? In my code, I have
$('.' + Key).closest( '.' + Key ).css("color", "#000");
This code works just fine, but the one in the jsfiddle does not.
closest traverses up the DOM and is used for nested elements.
In your markup, your div is not a descendant of your span, not even a sibling.
You have
1. To retrieve the previous sibling (the first li after the body)
2. And find the span inside the li
$(document).ready(function() {
$(".sub").prev().find('span').text('-');
});
Also, in your fiddle, you forgot to include jQuery.
Here is a working code : https://jsfiddle.net/qwc6pepr/1/
Incorrect function: .closest( selector ) Returns: jQuery
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree
What you want is the prev which finds the first sibling prior to the element
$(document).ready(function() {
$('.sub').prev('li').find('span').text('-');
});
From jQuery documentation
Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements
Your span is neither a Parent Element of your div.sub in the DOM, nor matches with the $(".sub") rule.
The only way to make your jQuery code work with your HTML structure :
$("#plusMinus1").text("-");
Or modify your HTML structure to match with the .closest() method requierements
Fiddle
When you go to the parent you'll end up in the body. From there you can find the span.
$(document).ready(function() {
$(".sub").parent().find("span").text("-");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<body>
<li>
<a class="selected" href="#" onclick="return false;">Dashboard 1 <span id="plusMinus1">+</span></a>
</li>
<div class="sub">
<ul>
<li><a id="s1" href="">Test A</a>
</li>
<li><a id="s2" href="">Test B</a>
</li>
<li><a id="s3" href="">Test C</a>
</li>
</ul>
</div>
</body>

jquery find element considering parent

How can I find an element considering parent node? Example:
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
var $ul = $('.ul');
console.log($ul.find('.item-1')) - // found - OK
if find
console.log($ul.find('.level-3')) - // not found - WHY ???
Assuming UL as element
You are not able to find it as level-3 is not the child of ul.
As per your current HTML, You need to use .filter()
Reduce the set of matched elements to those that match the selector or pass the function's test.
Code
var $ul = $('ul');
$ul.filter('.level-3')
You can use soma kind of jQuery functions to do this:
Closest: find the anchestor element matches the selector.
The .closest() method begins its search with the element itself before progressing up the DOM tree
Parents: walk the DOM tree looking for all parents that matches the selector.
is: check if the element match the selector.
$ul.closest(".level-3")
In your point you don't have ".level-3" class. For simply you can use jquery to do this.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
alert($("ul").find('.item-3').text());
});
});
</script>
</head>
<body>
<ul class="level-3">
<li class="item-1">1</li>
<li class="item-2">2</li>
<li class="item-3">3</li>
</ul>
<button id="btn1">Show level 3 Text</button>
</body>
</html>

Difference between $('selector')[0] ,$('selector').eq(index) in jquery.

What is the difference between $('#div1 a')[0] and $('#div1 a').eq(0) for the following markup
<div id="div1">
click
</div>.
Please Help.
$('div1 a')[0]
returns a direct reference to a DOM element
$('div1 a').eq(0)
returns a JQuery object
http://jsfiddle.net/meo/DP8as/
This will not work:
$('div a')[0].hide()
this will;
$('div a').eq(0).hide()

What is the difference between .empty().append() and .html()?

Using jQuery, what's the performance difference between using:
$('#somDiv').empty().append('text To Insert')
and
$('#somDiv').html('text To Insert')
?
$('#somDiv').html(value) is equivalent to $('#somDiv').empty().append(value).
Source: jQuery source.
.html will overwrite the contents of the DIV.
.append will add to the contents of the DIV.
difference between append() and html() in jQuery
.append() and .html() are the most useful methods in jQuery. But these are far different from one another, .append() add some value to the existing one. Where .html() do the same but it removes the old value first.
Here is an example:
<ul id="test">
<li>test</li>
</ul>
Now I will use .append() to add one <li>, For that I will write:
<script type="text/javascript>"
jQuery("#test").append("<li>test1</li>");
</script>
The output of this jQuery will be:
<ul id="test">
<li>test</li>
<li>test1</li>
</ul>
Now if I use .html() to add one <li>, For that I will write:
<script type="text/javascript>"
jQuery("#test").html("<li>test1</li>");
</script>
The output of this Script will be:
<ul id="test">
<li>test1</li>
</ul>
Here in this example .append() add one extra <li>, whether .html() removes the old one with new one. This is the main difference between .append() and .html() in jQuery.
In simple words:
$('#somDiv').append('blabla')
works like this:
<div id='somDiv'>some text</div>
becomes:
<div id='somDiv'>some textblabla</div>
And innerHTML replaces the contents, so it becomes this:
<div id='somDiv'>blabla</div>
The correct syntax is
$("#somDiv").html("<span>Hello world</span>");

Categories

Resources