How can i read the last element id using javascript?
for example :
<div id='print'>
<p id=1>some data</p>
<p id=2>some data</p>
<p id=3>some data</p>
<p id=4>some data</p>
<p id=5>some data</p>
</div>
I need to detect the id of last
I need max number of the id actually.it's generated sequentially.
First off, id values cannot be numbers. They must start with a non-number.
You can get the last child with this plain javascript (no jQuery required):
var lastChild = document.getElementById("print").lastChild;
var lastChildID = lastChild.id;
or in one line, it would be this:
var lastChildID = document.getElementById("print").lastChild.id
FYI, in case you need access to any other children you can always get all the children and then fetch the one you want:
var children = document.getElementById("print").children;
if (children.length > 1) {
var first = children[0];
var last = children[children.length - 1];
var second = children[1];
}
Now that you've explained what you're really trying to do, I'd suggest this:
<div id='print'>
<p data-num="1">some data</p>
<p data-num="2">some data</p>
<p data-num="3">some data</p>
<p data-num="4">some data</p>
<p data-num="5">some data</p>
</div>
And, then this javascript:
var lastValue = document.getElementById("print").lastChild.getAttribute("data-num");
Using the data-xxx format is forward compatible with the HTML5 specification and usable in older browsers with getAttribute().
Try this:
getElementById('print').lastChild.id;
If you use jQuery you could do something like this $("div#print :last-child").attr('id')
In jQuery you can simply use their selectors to find this:
$("p").last().attr("id");
Try this way:-
$('p:last').attr('id')
OR
$('div#print p:last').attr('id')
Related
How to find out the element which does not contain any class?
<p>You will receive the ebook in your email</p>
<p class="active">You will NOT receive the ebook in your email</p>
I want to find the paragraph element which does not contain any class.
Sample code is much appreciated.
Keep Coding...
You can use the :not() pseudo class:
let matches = document.querySelectorAll('p:not([class])');
for (let p of matches) {
console.log(p.textContent);
}
<p>You will receive the ebook in your email</p>
<p class="active">You will NOT receive the ebook in your email</p>
If you want to also match elements that have the class attribute, but which is still empty, then add that in the selector: p:not([class]), p[class=""]. Of course, you can then also think of a class attribute that has just space(s), ...etc.
You could filter your paragraphs by the length of their classList
var allParagraphs = Array.from(document.querySelectorAll("p")).filter(({classList}) => classList.length === 0)
console.log(allParagraphs)
//for older browsers
var allP = [];
document.querySelectorAll("p").forEach(function(el) {
if(el.classList.length === 0) allP.push(el);
})
console.log(allP);
<p>no class</p>
<p>nope</p>
<p class="df">öldskjf</p>
<p class="ölsdf">slkdf </p>
I am trying to figure out how to display number a right and efficient way for later calculation in HTML. This is what i can think of right now but doesn't seems right.
<p class = "price"> <span class ="sign">$</span> 10 </p>
Later implementation includes
$("p.price") * (the desire currency rate being called)
It then updates the whole page with the p.price
Consider using data attributes:
<p class="price" data-usd-price="10"> any markup you want </p>
You can then format it however you like and access the raw value later with:
$("p.price").data("usd-price")
Here a bit more complicated example:
<p class="price" data-usd-price="10">foo<span class="converted"></span></p>
<p class="price" data-usd-price="30">bar<span class="converted"></span></p>
<p class="price" data-usd-price="49.99">buzz<span class="converted"></span></p>
<p class="price" data-usd-price="99.99"><span class="converted"></span></p>
$('p.price').each(function () {
$(this)
.children('span.converted')
.html(
$(this).data('usd-price') * 22
)
})
The selector $("p.price") will give you an array of all paragraph elements with the class price. So your first issue is that you need to be aware of that, and your current multiplication code is not.
Second, you're trying to multiply the elements rather than the value of the one element.
Third, the value will be a string and you need a number.
I'd try something like:
<p class="price"><span>$</span><span class="amount">10</span>
Then your JS could look like this (minus smart error checking and optimization and such)
var amount = parseFloat($("span.amount:first").text(), 10);
$("span.amount:first").text(amount * exchangeRate);
Try to loop through paragraph children and check, if nodeName of the children is text then parse it's wholeText
var pContent = $('.price')[0].childNodes,
elem, num;
$.each(pContent, function (i, e) {
elem = $(e)[0];
if (elem && elem.nodeName == "#text") {
num = parseInt(elem.wholeText);
}
})
console.log(num)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<p class = "price"> <span class ="sign">$</span> 10</p>
when the page load the span is left empty but i want it to be shown (GBP as the base)
Simply change the spans text on window load instead of onchange event
var selectedIndex = select.selectedIndex;
$('.sign').text(prefix[selectedIndex ]);
$('.converted').text(currency[selectedIndex ] * $(price).data('price'));
Also i have some notes, if you have just one element you don't need to implement each function , and you don't need to make loop on each change as selectedIndex will filter the option which has selected attribute. http://jsfiddle.net/whoq9zd0/2/
I'm trying to find all oferts in the var articleFirst, but the return message in the console says that "querySelectorAll" is not a function. Why I do get that error?
This is my HTML:
<article class="first">
<div class="feature parts">
<div class="oferts">
<div class="heart icons"></div>
<h1>Build with passion</h1>
</div>
</div>
</article>
This is my JavaScript:
var articleFirst = document.querySelectorAll("article.first");
var oferts = articleFirst.querySelectorAll(".oferts");
Error:
Uncaught TypeError: articleFirst.querySelectorAll is not a function
Try do do this:
var articleFirst = document.querySelectorAll("article.first");
console.log(articleFirst)
var oferts = articleFirst[0].querySelectorAll(".oferts");
console.log(oferts)
With console you can see what is happening.
Or just do this:
document.querySelectorAll("article.first .oferts");
querySelectorAll is a method found on Element and Document nodes in the DOM.
You are trying to call it on the return value of a call to querySelectorAll which returns a Node List (which is an array like object). You would need to loop over the Node List and call querySelector all on each node in it in turn.
Alternatively, just use a descendant combinator in your initial call to it.
var oferts = document.querySelectorAll("article.first .oferts");
You need to use document.querySelector instead of document.querySelectorAll because the next query depends on a single HTMLElement but document.querySelectorAll returns a NodeList.
document.addEventListener('DOMContentLoaded', TestCtrl);
function TestCtrl() {
var firstArticle = document.querySelector('article.first');
console.log('oferts', firstArticle.querySelectorAll('.oferts'));
}
<article class="first">
<div class="feature parts">
<div class="oferts">
<div class="heart icons"></div>
<h1>Build with passion</h1>
</div>
</div>
</article>
A little verbose but you could try qselectorAll('article') then turn that nodeList into an array and pick the first index.. so something like:
let articleList = querySelectorAll('article'); // makes a NodeList of all article tags on the webpage
let article = Array.from(articleList);
article[0];
I am having a trouble for fetching innerHTML of the following two strong tags
<div>
<strong>data 1</strong>
<span class="and">and</span>
<strong>data 2 </strong>
</div>
<div>
<strong>data 3</strong>
<span class="and">and</span>
<strong>data 4 </strong>
</div>
i want to get data1, data2 in console but i'm unable to achieve anything.
I have tried document.querySelector("strong") but it just provide me data1.
How can i fetch data2 data3 & data4 from other strong tag?
Any help is appreciated.
i know i can do
document.getElementsByTagName("strong")['increment_operator'].innerHTML;
and
document.querySelectorAll("strong");
querySelector finds the first result and stop searching whereas querySelectorAll finds all.
Try code below to log html of strong tag:
var elems = document.getElementsByTagName('strong');
for (i=0;i < elems.length;i++{
console.log(elems[i].innerHTML)
}
To get innerHTML of the last strong tag in html run code below:
var elems = document.getElementsByTagName('strong')[:1];
console.log(elems[elems.length-1].innerHTML);
If you have same tag and you want specific tag innerHTML then give unique ids and then try to fetch or if you want to fetch all strong tag innerhtml then use queryselectorall()
As example
<div>
<strong>data 1</strong>
<span class="and">and</span>
<strong>data 2 </strong>
</div>
<div>
<strong>data 3</strong>
<span class="and">and</span>
<strong>data 4 </strong>
</div>
var a = document.querySelectorAll("strong");
for (var i = 0; i < a.length; i++) {
alert(a[i].innerHTML);
}
Summing up the partials:
The document.querySelector(commaSeperatedStringOfSelectors) only finds the first node in the documentsatisfying the selectors it is given. So you need to be more specific with it, need to supply some queryable selectors to your html elements, like id class.
But if you want to select more widely follow:
document.querySelectorAll(commaSeperatedStringOfSelectors) to get an array of all the nodes satisfying the selectors. Then you can select the element you need by index. fiddle
Or you need to use #Andriy Ivaneyko's answer style, use getElementByTagName('tagname'), getElementsByClassName('class'), or getElementById('id').
Note: document.querySelectorAll(commaSeperatedStringOfSelectors) is more versatile, it gives you opportunity to be both more specific or more unspecific. You can use a string like that in it: 'strong, div.animals, a'.
Ok i did my job by doing following.
var divLength = document.getElementsByTagName("div").length;
var z = 0;
for(i=0; i<divLength; i++){
var dataFromFirstStrong = document.getElementsByTagName("strong")[z].innerHTML;
z++;
var dataFromSecondStrong = document.getElementsByTagName("strong")[z].innerHTML;
z++;
}
I'm new to javascript/jQuery and am attempting something ambitious for my skill level. I found some snippets that have helped but am stuck.
I have a bunch of dates in the format like this: dd-month-yyyy (10-Oct-2013). As far as I understand this is somewhat of an unconventional format for a date. So what I'm trying to do is parse the date into a normal format, and then arrange the parent divs using the jQuery tinysort plugin (which I don't think I am using correctly).
I made a jsfiddle here: http://jsfiddle.net/8BYDZ/
Or here is my code:
<div id="date-sort">
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">10-Oct-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">12-Oct-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">2-Sep-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">22-Jun-2013</p>
<hr />
</div>
<div class="date-content">
<p>Some Content</p>
<p class="date-sort">1-May-2013</p>
<hr />
</div>
</div>
$(document).ready(function(){
function customParse(str) {
var months = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'],
n = months.length, re = /(\d{2})-([a-z]{3})-(\d{4})/i, matches;
while(n--) { months[months[n]]=n; } // map month names to their index :)
matches = str.match(re); // extract date parts from string
return new Date(matches[3], months[matches[2]], matches[1]);
}
var array = [];
var elements = $('.date-sort');
for(var i = 0; i < elements.length; i++) {
var current = elements[i];
if(current.children.length === 0 && current.textContent.replace(/ |\n/g,'') !== '') {
// Check the element has no children && that it is not empty
customParse(current.textContent);
array.push(current.textContent);
}
}
$('div#date-sort>.date-content>.date-sort').tsort();
});
Thanks for any help, insight, or input.
You need to give tinysort a sortable date.
new Date(matches[3], months[matches[2]], matches[1]).toJSON();
// ...
current.setAttribute('data-date', customParse(current.textContent));
// ...
$('div#date-sort>.date-content').tsort('.date-sort', {attr: 'data-date' });
Your regular expression was too restrictive as days are not always two numbers.
re = /(\d{1,2})-([a-z]{3})-(\d{4})/i
Here is a working jsiddle
You simply need to eliminate the - marks with .replace(), then by using new Date().getTime() you assign the number of milliseconds between midnight of January 1, 1970 and your Dates to an Array that will .sort() just how you need it to.
$(document).ready(function(){
var ds = $('.date-sort'), dt = [];
ds.each(function(i){
dt[i] = new Date($(this).html().replace(/-/g, ' ')).getTime();
});
dt.sort();
ds.each(function(i){
$(this).html(new Date(dt[i])/*add . whatever here*/);
});
});
I updated your JSFiddle.
In JavaScript, objects are generally considered the best way to create associative maps (as the commentors pointed out below, it's perfectly valid to set a property on an array).
I would use an object as your map between month names and numbers. Also, I would use lowercase names, so I could pay the cost of lowercasing once, and use that value in my mapping.
So I would replace the definition of your months array with an object initializer:
var months = { 'jan': 1, 'feb': 2, 'mar': 3, /*...*/ };
In that way, you don't need the loop.
Now you just need to call .toLowercase() on your input, and the month names will map correctly.