Get data attribute value of the Nth element using jQuery - javascript

I am trying to get the data attribute value of the first element from the elements matched by this jQuery selector but it is giving me an error:
$("p.expiryItem").get(0).attr("data-id")
Uncaught TypeError: $(...).get(...).attr is not a function(…)
Yet it works with this:
$("p.expiryItem").attr("data-id")
What if I want to use the Nth element? Thanks

The problem is because although get(N) returns the Nth element in the matched set, it returns the underlying DOMElement which does not have an attr() method and hence the error.
To fix this you could use eq() which does the same job, but returns the element in a jQuery object:
$("p.expiryItem").eq(0).data('id') // zero-based
Or you could use the :nth-child selector:
$("p.expiryItem:nth-child(1)").data('id') // one-based
Note the preferred use of data() here to retrieve the data-* attribute.

$("p.expiryItem:nth-child(1)").attr("data-id")
Use selector :nth-child()
note that it starts with 1
Description: Selects all elements that are the nth-child of their parent.

Use eq(n).
difference between get(n) and eq(n) is that get returns JavaScript reference to the element, but eq returns jQuery object, which has the function attr().
$("p.expiryItem").eq(n).attr("data-id");
PS:
You can use data() function for data-attributes.
$("p.expiryItem").eq(n).data("id");

You can use .eq() jQuery method.
Eg.
HTML :
<p class="expiryItem" id="1">1</p>
<p class="expiryItem" id="2">2</p>
<p class="expiryItem" id="3">3</p>
<p class="expiryItem" id="4">4</p>
<p class="expiryItem" id="5">5</p>
JavaScript :
//For 2nd `p`
console.log("Attribute value of 2nd : "+$("p.expiryItem").eq(1).attr("id"));
//For 5th `p`
console.log("Attribute value of 2nd : "+$("p.expiryItem").eq(4).attr("id"));
JSFiddle

Related

How do we convert jQueryn $li.find('div.element:first') in VanillaJS

Does querySelectorAll() accept ('div.element:first') this type of argument? I need to convert below jQuery method in VanillaJS
jQUery :
$li = $(this)
$li.find('div.element:first')
Vanilla :
var li = event.target;
li.querySelectorAll('div.element:first');
But the Vanilla script is not working as same as jQuery. Someone please suggest any better solution
jQuery's :first reduces the set of matched elements to the first in the set.
In other words, you get the first element matching div.element.
To do the same in plain javascript, all you have to do is call querySelector without the All part
var first = li.querySelector('div.element');
As querySelector will return the first element that matches the specified selector anyway
This of course only works if li is a single element, querySelector doesn't work on collections the way jQuery's find() does.
If li is not a single element, you have to iterate, but since you're only looking for the first element, you could just do
var first = li[0].querySelector('div.element');

Select all the elements within an element having an attribute set to a specific value

I have the followings defined :
var excludedFiltersPanel = $("#excludedFiltersPanel");
var includedfiltersPanel = $("#includedfiltersPanel");
where *Panel is just a div.
in excludedFiltersPanel there are some div's with attribute data-iscorefilter="true" e.g. :
<div id="filterPanel-LastName" class="filterPanel" data-iscorefilter="true">
<Some Stuff here!>
</div>
I am trying to get them and move them to includedfiltersPanel:
It seems neither of these is a correct syntax:
excludedFiltersPanel.('[data-iscorefilter="true"]')
excludedFiltersPanel.$('[data-iscorefilter="true"]')
1.What is the correct syntax?
2.How do I append them to includedfiltersPanel? (I know how to append a single item, but not sure what is the common good practice here, e.g. using for loop or some JQuery magic)
Since excludedFiltersPanel there are some div's with attribute data-iscorefilter="true"
Use .find()
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
It would look like :
excludedFiltersPanel.find('[data-iscorefilter="true"]')

I am unable to a inserting the content HTML pre tag

Function objective()
{
Document.getelementbyid("pre").innerhtml=""
}
And in the HTML for my li in nave, I declared the onclick function but it is not working.
Note:- I am clear about case sensitivity in js and using bootstrap3
for resposive.
Use document.getElementsByTagName instead. This will return an array of all the elements that have that tag name.
Due to it returning an array, you need to make sure you use [0] to find the first index in the array.
function objective(){
document.getElementsByTagName("pre")[0].innerHTML="";
}
objective();
<pre>This is some content that will not show in the snippet</pre>
<div>This content will though</div>
getelementbyid() expect a id, not a tag name,your code will call on html like
<pre id="pre">
</pre>
if you want to select elementnot by id but form tag name use document.querySelectorAll("pre")[0] or document.querySelector("pre")
remember querySelectorAll return an array!!
getElementById selects an element with defined id as in your case pre as an id.
You must have an id attached to your element same that of argument in getElementById().
Or, you can use getElementsByTagName which selects element given in argument.

Jquery select previous element with class

I have 3 elements:
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>
on click on target div I test .prev() function in my js
$(document).on('click','.target',function(){
console.log($(this).prev().html());
console.log($(this).prev('.first').html());
});
Output is like: 'Second undefined', but should be like: 'second first' if I understand right the parameter of .prev() usage.
How can I get first previous element with certain class then?
Here is fiddle for you: http://jsfiddle.net/0fzgzce5/
From jQuery docs,
.prev()
Description: Get the immediately preceding sibling of each element in
the set of matched elements, optionally filtered by a selector.
To select all preceding sibling elements, rather than just the
preceding adjacent sibling, use the .prevAll() method.
http://api.jquery.com/prevAll/
So you should use console.log($(this).prevAll('.first').html());
You can make use of sibling() which will return the element with specific class and at same level as calling elment. But make sure that there is no same div after target
$(document).on('click','.target',function(){
console.log($(this).siblings('.second').html());
console.log($(this).siblings('.first').html());
});
DEMO
OR you can use prevAll()
$(document).on('click','.target',function(){
console.log($(this).prevAll('.second').html());
console.log($(this).prevAll('.first').html());
});
DEMO
Use prevAll() instead of prev()
$(document).on('click', '.target', function() {
alert($(this).prevAll('.second').html());
alert($(this).prevAll('.first').html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='first'>First</div>
<div class='second'>Second</div>
<div class='target'>Target</div>
You can use also $("div:eq(3)") to get the exact element. Best example is $("ul li:eq(3)")
In your second console.log(), yous this is still .target and it does not have .first class so it is saying undefined.
To get the first dive, do:
console.log($(this).prev().prev().html());
Jquery .prev() always get immediate preceding sibling.
if you pass a selector as parameter it will filter the preceding element to match with, if it did not match it will return undefined, in your case this is happening
$('.target').prev().html()
is same as
$('.target').prev('.second').html();
which will return "Second"
If you pass any selector other than '.second' it alway return undefined so, your case
$('.target').prev('.first').html();
is as exprected, returning undefined because '.first' is not matching with preceding element selector.
Update:
if you want to get First the use
$('.target').prev().prev().html();

Get class of forth cell adjacent to current cell

I am trying to get class of fourth cell using eq() selector. Its working without eq selector like this :
alert($cell.closest( "td" ).next().next().next().attr("class"));
I tried using multiple variation of eq() but it's not working please help.
None of the below are working.
$cell = $(this);
alert($cell.find( "td" ).eq(3).attr("class"));
alert($cell.closest( "td" ).eq(3).attr("class"));
alert($cell.( "td:eq(3)" ).attr("class"));
That's not how the eq method work.
Given a jQuery object that represents a set of DOM elements, the .eq() method constructs a new jQuery object from one element within that set. The supplied index identifies the position of this element in the set.
As the closest method returns one element, eq(3) returns an empty set in here. You can use the nextAll method for creating a set of next siblings. Then eq(3) will return the fourth element in that set:
$cell.closest("td").nextAll().eq(3).attr("class");
Please note that if this here refers to a td element then closest('td') does nothing.

Categories