How do I combine javascript variable to jquery selector? - javascript

I am trying to get the table td texts by using Jquery and javascript
I have the following
//tables contain bunch of tables
for(var i = 0; i < tables.length ; i ++){
var table = tables[i];
$(table 'td').each(function(){ //I know there is something wrong with my selector.
$(this).text()
})
The jquery selector doesn't work in my case. How do I select every td for different table?
Thanks for the help!

I think you want to use the .find() method:
$(table).find('td').each(function(){
DEMO: http://jsfiddle.net/jfj47/
Of course, an alternative is to use the "context selector":
$("td", table).each(function(){
DEMO: http://jsfiddle.net/jfj47/1/
Also, if tables is just an array (or array-like object) of DOM elements, you don't have to loop and could use:
$(tables).find("td").each(function(){
DEMO: http://jsfiddle.net/jfj47/2/
References:
find(): http://api.jquery.com/find/
context selector: http://api.jquery.com/jQuery/

Related

How to select attributes from a list of divs in jquery?

I have 16 divs with the class "box" and each "box" has a different name.
The first "box" has name="box1";
the second "box" has name="box2";
the third "box" has name="box3";
and so on.....
I want to select these individual names, so I attempted to use the following code:
for (var i = 0; i < $(".box").length; i++) {
console.log($(".box")[i].attr("name"));
}
But my console shows that "$(...)[i].attr is not a function".
When I tried this:
for (var i = 0; i < $(".box").length; i++) {
console.log($(".box").attr("name"));
}
I get back 16 lines of "box1", which is only the name for the first "box" div.
What I want instead is "box1, box2, box3, box4, box5..."
What can I do?
Using jQuery:
$( ".box" ).each(function( index ) {
console.log($(this).attr("name") );
});
Does it have to be jQuery? If not, this could work:
[...document.querySelectorAll('.box')]
.map(d => d.getAttribute('name'))
.forEach(name => console.log(name))
You can do it using jQuery eq
for (var i = 0; i < $(".box").length; i++) {
console.log($(".box").eq(i).attr("name"));
}
or using fully jQuery version
$('.box').each(function(){
console.log($(this).attr('name'));
})
Please note that name is not a supported attribute on div elements, hence making your HTML invalid. Use data-name instead. Once you changed that, that also makes the code easier:
$(".box")[i]
gives you the native DOM element in the jQuery collection, which does not have any jQuery methods like attr(). It does, tho, have the native DOMElement dataset API, so you can simply go with
$(".box")[i].getAttribute('data-name')
or, even simpler
$(".box")[i].dataset.name
If you insist on using jQuery and also on using an index-based for-loop (which I haven't used in years now), go with jQuery's eq(index) function:
$(".box").eq(i).data("name")
As with almost everything, jQuery is just unnecessary bloat you don't need any longer in 2020. Here's the modern way to achieve your goal:
document.querySelectorAll('.box')
.forEach(el => console.log(el.dataset.name);

jQuery variable (select in html)

I'm new in Jquery, and I have this code:
jQuery(document).ready(function(){
var title = jQuery(".fullVisaImg").attr("inselect");
var links = jQuery(".ff_elem>option");
for(var i=0; i<links.length; i++) {
if (title == links[i].value) {
links[i].attr("selected", "selected"); // here is my problem
alert(links[i].value);
return;
}
}
});
i have a select element on my pages, and want to make one of elements selected. if I comment line with // here... all works good, and i see all my option values.
Thanks for help!
When you use [] to access an element in a jquery set, you get back the raw DOM element. So you can not use jquery methods on it directly..
You should also use .prop instead of .attr() when interacting with properties of the element
So use
links.eq(i).prop("selected", true);
replace you for loop with:
jQuery(".ff_elem").val(title);
I have created this DEMO for you. Check it out.
Although You can iterate through all your option elements and find your option element, and then do this:
links[i].prop("selected", true);
but there is no need to iterate when you can simply let your select element do this for you as I have mentioned above.
This is actually how you can select an option based on the value your options have.
$('select').val('value of the option you want to select');
so use
$(".ff_elem").val(title);
Following your code, you could use:
links.eq(i).prop("selected", true);
if your jquery version is above 1.6+ then use this
links.eq(i).prop("selected", true);
else
links.eq(i).attr("selected", "selected");
It can be much simpler. Try something like this:
jQuery(document).ready(function(){
var title = jQuery(".fullVisaImg").attr("inselect");
jQuery(".ff_elem>option[value=" + title + "]").attr("selected", "selected");
});
links is a jQuery collection. When you loop through it, you're just getting the raw element, not a jQuery wrapped version, so you can't use .attr().
Use this instead at your problem line.
$(links[i]).attr("selected", "selected");

adding classes (serially numbered) to each DIV on page automatically via javascript?

i'm running a contact-form-plugin on my wordpress installation. everything works fine but i want to style my form a little bit more. to do it like this i have to style some DIVs (which the plugin is processing) in a different way. the problem is: all DIV-containers have no IDs or classes! everything is processed by the plugin and my PHP-skills are like zero so i have to deal with this "naked" DIVs ;-)
the question is: is it possible to add serially numbered classes to each DIV on the current site via javascript?
thanks so far and i hope you get waht i mean (sorry for that shitty english)!
Yet another way, passing a callback to .attr [docs]:
$('div').attr('class', function(i) {
return 'someClass' + i;
});
Though you could also use this for IDs instead, since each class will be unique.
Note that you don't have to use IDs or classes to select elements, there are a number of selectors and traversal methods with which you can get a reference to the elements you want.
To prevent overriding existing classes, either select only the elements with no class or somehow narrow down the selection of divs to only those you want:
$('div:not([class])')
or use .addClass [docs] instead of .attr:
$('div').addClass(function(i) {
return 'someClass' + i;
});
You need something like this,
Live Demo
$('div').each(function(i, item){
$(this).attr('class', "YourClass" + i); //You can replace i with some other variable if required and increment it.
});
You could do this:
var divs = document.getElementsByTagName("div");
var className = "myClass";
for( var i = 0, max = divs.length; i< max; i++ ){
divs[i].setAttribute("class",className + i.toString());
}

Getting the last row of a table using jQuery?

I'm dynamically creating table rows. So each time I add a row, I need to get the ID of the last <tr> so that I can create a new <tr> with ID = "(the last row's ID) + 1". Is there any way to get the last row's ID using jQuery?
$('#yourtableid tr:last').attr('id');
Old question, but here's a different way using JQuery traversal which is a bit quicker:
$("#TableId").find("tr").last();
An alternative method to ID your rows, if they are all sequential is just to get the number of rows + 1.
$("#TableId").find("tr").length + 1
var id = $('table tr:last').attr('id');
2019
As of jQuery 3.4.0 :last is deprecated, use .last() instead, like this:
var id = $('#mytable tr').last().attr('id');
var tid=$('#tableid tr:last').attr('id');
alert(tid);
There are two methods and they both work $('#tableid tr:last') and $('#tableid tr').last()
You don't need to use jQuery for that. You can handle it in CSS counters. The counters automatically increments the index values and it also handles the rearrangement of numbers in case a row is deleted from the midst. The CSS counters can be implemented as follows. Insert it into your CSS file that take care of the styles of the HTML table.
#yourtableid tbody
{
counter-reset: tablerow;
}
#yourtableid tbody .yourHTMLcellclass::before
{
counter-increment: tablerow;
content: counter(tablerow)". ";
}
Last row id of table
var lastid = $('table tr:last').attr('id');
var str = lastid .replace(/[^0-9]+/ig,"");
I was looking for a Vanilla javascript solution and this question is the first Google result, so here is the solution without Jquery :
let table = document.getElementById('myTable') ;
let lastLine = table.rows[table.rows.length-1];

How to get all elements between html tag?

I want to get all elements from the web page.i used form id or name to get all elements but if there is no form id or name i can't get elements from that page.what is the alternate for this problem. please help.
You can retrieve an array of all nodes in a html document using document.getElementsByTagName('*'). After that you can iterate through that array:
var allElements = document.getElementsByTagName('*');
for (var i=0;i<allElements.length;i++){
//do things with the element, e.g.
//console.log(allElements[i].type)
//console.log(allElements[i].id)
//console.log(allElements[i].innerHTML)
}
Update 2014: a more modern approach would be
var allEls = [].slice.call(document.querySelectorAll('*');
allEls.forEach( function (el) {
//do things with the element, e.g.
//console.log(el.type)
//console.log(el.id)
//console.log(el.innerHTML)
});
You can use jQuery: $("html *") which will return all elements between the html tags
for names you must use $("html *").attr('name')
for values $("html *").val() or $("html *").attr('value')
Have heard of something called jQuery ? With the help of traversing API you can get to an element you want. Here is the complete list of API - http://api.jquery.com/
You can use the jQuery selectors like: $("*") .This particular selector will return all the elements(tags) of that html page.
maybe you can try this: document.childNodes
no framework, lib needed.

Categories

Resources