Get the last occurrence of an element [duplicate] - javascript

This question already has answers here:
Get multiple elements by Id
(14 answers)
Closed 5 years ago.
getElementById(id) returns the element with the matching ID attribute. How can I get the last occurrence of this element, as opposed to the first?
<!DOCTYPE html>
<html>
<body>
<button onclick="getLast()">Click me</button>
<div id="username">Lisa</div>
<div id="username">Chris</div>
<script>
function getLast() {
alert(document.getElementById("username").innerHTML);
}
</script>
</body>
</html>

id is always unique. No two DOM elements can have the same id. In your case use the class attribute. Use getElementsByClassName which will return a collection. Get its length and use that value to get the last element.
function getLast() {
var getLastElemIndex = document.getElementsByClassName("username").length - 1;
console.log(getLastElemIndex)
alert(document.getElementsByClassName("username")[getLastElemIndex].innerHTML);
}
<div class="username">Lisa</div>
<div class="username">Chris</div>
<button onclick="getLast()">Click me</button>

id should be unique. But we don't have control on how people write their code and I also meet this case sometimes: "I need to parse the page and they are using same id"
You can treat id as an attribute and use querySelectorAll:
<button onclick="getLast()">Click me</button>
<div id="username">Lisa</div>
<div id="username">Chris</div>
<script>
function getLast() {
tags = document.querySelectorAll('[id="username"]');
alert(tags[tags.length - 1].innerHTML);
}
</script>
And the best practice should be using class.

The id of a HTML element is meant to be unique. You should specify the class instead:
<div class="username">Lisa</div>
<div class="username">Chris</div>
Then use Document.getElementsByClassName() to get all elements of that class:
var usernames = document.getElementsByClassName("username");
Alternatively, you can use Document.querySelectorAll():
var usernames = document.querySelectorAll(".username");
And then you can get the last one:
var lastUsername = usernames[usernames.length - 1];

Even you can do it by tag name div, as #brk said id must be unique.
function getLast(){
var divs = document.querySelectorAll("div");
console.log(divs[divs.length - 1].textContent);
}
getLast();
<button onclick="getLast()">Click me</button>
<div>Lisa</div>
<div>Chris</div>

Related

How do I change more than one element?

EDIT: I changed the var to class but I might have some error in here.
Here it goes, I want to have this paragraph in which the user can change the name on the following paragraph. The code I'm using only changes one name but the rest remains the same.
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
<input id="userInput" type="text" value="Name of kid" />
<input onclick="changey()" type="button" value="Change Name" /><br>
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
No error messages, the code only changes one name instead of all three.
Use class="kiddo" instead of id in the html.
You can then use var kiddos = document.getElementsByClassName('kiddo') which will return an array of all the elements of that class name stored in kiddos.
Then you just need to loop through the values and change what you want.
Example of loop below:
for (var i = 0; i < kiddos.length; i++) {
kiddos[i].innerHTML = userInput;
}
id should be unique on the page. Javascript assumes that there is only one element with any given id. Instead, you should use a class. Then you can use getElementsByClassName() which returns an entire array of elements that you can iterate over and change. See Select ALL getElementsByClassName on a page without specifying [0] etc for an example.
Hello You should not use id, instead use class.
Welcome to the site <b class="kiddo">dude</b> This is how you create a document that changes the name of the <b class="kiddo">dude</b>. If you want to say <b class="kiddo">dude</b> more times, you can!
After That on Js part :
<script type="text/javascript">
function changey(){
var userInput = document.getElementById('userInput').value;
var list = document.getElementByClassName('kiddo');
for (let item of list) {
item.innerHTML = userInput;
}
}
</script>
you should use class instated of id. if you use id then the id [kiddo] must be unique
In short, document.querySelectorAll('.kiddo') OR
document.getElementsByClassName('kiddo') will get you a list of elements to loop through. Take note of querySelectorAll, though - it uses a CSS selector (note the dot) and doesn't technically return an array (you can still loop through it, though).
See the code below for some full working examples (const and arrow functions are similar to var and function, so I'll put up a version using old JavaScript, too):
const formEl = document.querySelector('.js-name-change-form')
const getNameEls = () => document.querySelectorAll('.js-name')
const useNameFromForm = (formEl) => {
const formData = new FormData(formEl)
const nameValue = formData.get('name')
const nameEls = getNameEls()
// Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(el => el.textContent = nameValue)
}
// Handle form submit
formEl.addEventListener('submit', (e) => {
useNameFromForm(e.target)
e.preventDefault() // Prevent the default HTTP request
})
// Run at the start, too
useNameFromForm(formEl)
.name {
font-weight: bold;
}
<!-- Using a <form> + <button> (submit) here instead -->
<form class="js-name-change-form">
<input name="name" value="dude" placeholder="Name of kid" />
<button>Change Name</button>
<form>
<!-- NOTE: Updated to use js- for js hooks -->
<!-- NOTE: Changed kiddo/js-name to spans + name class to remove design details from the HTML -->
<p>
Welcome to the site, <span class="js-name name"></span>! This is how you create a document that changes the name of the <span class="js-name name"></span>. If you want to say <span class="js-name name"></span> more times, you can!
</p>
var formEl = document.querySelector('.js-name-change-form');
var getNameEls = function getNameEls() {
return document.querySelectorAll('.js-name');
};
var useNameFromForm = function useNameFromForm(formEl) {
var formData = new FormData(formEl);
var nameValue = formData.get('name');
var nameEls = getNameEls(); // Set the text of each name element
// NOTE: use .textContent instead of .innerHTML - it doesn't get parsed, so it's faster and less work
nameEls.forEach(function (el) {
return el.textContent = nameValue;
});
};
// Handle form submit
formEl.addEventListener('submit', function (e) {
useNameFromForm(e.target);
e.preventDefault(); // Prevent the default HTTP request
});
// Run at the start, too
useNameFromForm(formEl);
<button class="js-get-quote-btn">Get Quote</button>
<div class="js-selected-quote"><!-- Initially Empty --></div>
<!-- Template to clone -->
<template class="js-quote-template">
<div class="js-quote-root quote">
<h2 class="js-quote"></h2>
<h3 class="js-author"></h3>
</div>
</template>
You have done almost everything right except you caught only first tag with class="kiddo".Looking at your question, as you need to update all the values inside tags which have class="kiddo" you need to catch all those tags which have class="kiddo" using document.getElementsByClassName("kiddo") and looping over the list while setting the innerHTML of each loop element to the userInput.
See this link for examples:https://www.w3schools.com/jsref/met_document_getelementsbyclassname.asp
try:
document.querySelectorAll('.kiddo')
with
<b class="kiddo">dude</b>

Printing all the id names for a class in javascript [duplicate]

This question already has answers here:
for loop works fine with console.log but not innerHTML?
(2 answers)
Closed 6 years ago.
I want print the Id of every element that has the class name "test". Right now nothing is printing. I would like this to print
myAnchor
SecondId
I left my comments in there to show how an Id can be printed by accessing the Id name
This is my script
<!DOCTYPE html>
<html>
<body>
<p><a id="myAnchor" class="test" href="http://www.w3schools.com/">W3Schools</a></p>
<p><a id="SecondId" class="test" href="http://www.w3schools.com/">Second</a></p>
<p>Click the button to display the value of the id attribute of the link above.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
//var x = document.getElementById("myAnchor");
//document.getElementById("demo").innerHTML = x.id;
var x = document.getElementByClassName("test");
for(count = 0; count < x.length; count++){
document.getElementById("demo").innerHTML = x.id;
}
}
</script>
</body>
</html>
You've just got a couple of basic typos:
document.getElementByClassName("test") should be document.getElementsByClassName("test')
document.getElementById("demo").innerHTML = x.id should be document.getElementById("demo").innerHTML += x[count].id
This is because the getElementsByClassName function returns an array of elements, so you need to get each element from the array, not the array itself.
Also, you were overwriting demo every time. Using the += operator rather than the = operator concats an string to the end of the original, rather than setting the original to the new string.
A few changes here:
Use getElementsByClassName() (instead of getElementByClassName, which isn't a function - unless you are defining it somewhere).
In order to access the id attribute of the element in the for loop, use x[count].id, since x is a NodeList and we need to access the element at index count. But for a simpler approach, use Array.forEach() (along with function.call, since the list of elements is a NodeList instead of a native Array instance) to iterate over the list of elements. That way the id attribute can be obtained via element.id instead of indexing into the array of elements manually. Also, you don't have to worry about incrementing the loop variable.
var testElements = document.getElementsByClassName("test");
Array.prototype.forEach.call(testElements, function(element) {
//access elements via callback argument element
});
As it is written with the for loop, you would need to access x[count].id in order to obtain the value of the id attribute.
Get a reference to the element with id demo outside the loop, then refer to that when adding to the innerHTML property.
var demo = document.getElementById("demo");
//in loop - refer to demo - e.g. demo.innerHTML
That way it won't be obtaining a reference to the DOM element each time it adds the id attribute value.
Add (append) to the innerHTML (string) property using the plus-equal operator (i.e. +=).
demo.innerHTML += element.id;
And you might likely want to separate those values (e.g. with a space, break tag (i.e. <br />), etc.
demo.innerHTML += element.id + '<br />';
See the changes implemented below:
function myFunction() {
var demo = document.getElementById("demo");
var testElements = document.getElementsByClassName("test");
Array.prototype.forEach.call(testElements, function(element) {
demo.innerHTML += element.id+'<br />';
});
}
<p><a id="myAnchor" class="test" href="http://www.w3schools.com/">W3Schools</a>
</p>
<p><a id="SecondId" class="test" href="http://www.w3schools.com/">Second</a>
</p>
<p>Click the button to display the value of the id attribute of the link above.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

How to handle spaces in div id in jquery

I am getting id of div from external source and in that spaces also coming in id , how to get the value of id. Here is my div example:
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>
I need to get the class name from the id. Here is what I am doing:
function AddValue(aa, bb) {
var classOfDiv = $('#123456ABC').attr('class');
var classOfDivs = $('#8904 bbc').attr('class');
alert(classOfDiv);
alert(classOfDivs);
}
The first alert is working fine but second is not fetching a value. How can I handle this? All the values are dynamic.
Use $("div[id='78904 bbc']") to access element which has spaces in id, Try:
var classOfDiv = $("div[id='123456ABC']").attr('class');
var classOfDivs = $("div[id='78904 bbc']").attr('class');
alert(classOfDiv);
alert(classOfDivs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="123456ABC" class="classname" onclick="javascript:AddValue(aa.value,'33',bb.value,'1000')"></div>
<div id="78904 bbc" class="classname1" onclick="javascript:AddValue(aa.value,'55',bb.value,'2000')"></div>

jquery - how can I select element after '.first()' using?

How can I select html tag after using jquery function called .first() ?
HTML
<html>
<head> </head>
<body>
<div>
<a>
<img id="#hello">
</a>
</div>
<div></div>
</body>
</html>
JS (JQuery)
var elemFirst = $(div).first();
var selectImg = elemFirst.$('img#hello');
// var selectImg = elemFirst.find('img'); <- It working but I want to select manual
selectImg.addClass('some-css');
With Respect
You can use $('child','parent') selector,
var elemFirst = $('div').first();
var selectImg = $('#hello',elemFirst); //or just $('img',elemFirst);
Also, your id has a #, it should be just id="hello".
If you need to keep this value in Id, use
var selectImg = $('img[id="#hello"]',elemFirst);
You can use find():
var selectImg = elemFirst.find('img#hello');
But you have an id of the image, so, you just can do this:
$('img#hello')
Because id is unique.
Use find()
elemFirst.find('img#hello');
This will search for direct and nested elements with the provided selector.
Alternatively, you can do
$('div:first #hello')
or even just
$('#hello')
since you are using an id which should be unique.
As in html the id be unique in html so striaghtly write
$("#\\#hello").addClass('some-css');
or
var selectImg = elemFirst.find('img[id="#hello"]');
Fiddle

JQuery: Convert to & from textarea element

I am new to JQuery & I am attempting to do some things which I am not sure I can do in JQuery.
Can I get a HTML elements type using a JQuery(or maybe even a native Javascript) function? If so, what is the name of the function?
I want to update/set a HTML elements class attribute. Would you suggest I use just plain old setAttribute() for this or should I use a JQuery function? If I should use a JQuery function whats the name of the function?
Is there a javascript function that returns a HTML elements class? Is it this.getAttribute("class");?
More experienced JQuery Programmers: How would you improve this JQuery HTML code that attempts to change elements to textarea's then back again(some functionality is missing right now):
<html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript">
<!--
var STATE = 0;
function Toggle()
{
if (STATE==1) { convertToUpdatable(); STATE = 0; }
else { convertToStatic(); STATE = 1; }
}
function convertToUpdatable()
{
// Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements
// and store their HTML element type in the class attribute
// EG: Before: <p class="updatable"/> Hello this is some text 1 </p>
// After : <textarea class="updatable p"/> Hello this is some text 1 </textarea>
$(".updatable").each(function()
{
$(this).replaceWith("<textarea>"+$(this).text() +"</textarea>");
// TODO store this elements type in class attribute
// The below is guessing that there are jquery functions getType()
$(this).setAttribute( "class", $(this).getAttribute("class") + $(this).getType() );
});
}
function convertToStatic()
{
// Post: Find all HTML elements (with the class 'updatable'), check to see if they are part of another class aswell
// (which will be their original HTML element type) & convert the element back to that original HTML element type
$(".updatable").each(function()
{
// This uses javascript functions: how can I write this in JQuery
var type = this.getAttribute("class").replace("updatable","").replace(" ", "");
if (type == "") { alert("Updatable element had no type defined in class attribute"); return; }
$(this).replaceWith( type +$(this).text() + type );
$(this).setAttribute( "class", "updatable" );
});
}
-->
</script>
</head>
<body>
<p class="updatable"/> Hello this is some text 1 </p>
<b class="updatable"/> Hello this is some text 2 </b>
<i class="updatable"/> Hello this is some text 3 </i>
<input id="MyButton" type="button" value="Click me!" onclick="Toggle();" />
</body>
</html>
Here are links for your first three questions:
How can I determine the element type of a matched element in jQuery?
http://api.jquery.com/addClass/
http://api.jquery.com/hasClass/
Javascript:
your_element.className = 'some_class';
your_element.nodeName;

Categories

Resources