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

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>

Related

DOM select all html content between two specific tags JS or JQuery

I have something like this in html:
<p class ="aa">Something<p>
<p class ="bb">Another thing<p>
<p class ="cc">Something else<p>
<p class ="aa">Things are coming<p>
<p class ="dd">Too much things<p>
<p class ="ee">Neverending things<p>
<p class ="aa">Best thing ever<p>
And I want to select and store in a variable every tags between two tags with the "aa" class. (The goal is to store each result in a JSON file)
How can I proceed with vanilla JS or Jquery?
Thank you for your response.
You can probably do something like this
let selectedTags = []
let allTags = document.querySelector(".aa").parentNode.children
for (let i = 1; i < allTags.length; i++) { //1 to skip the first aa element
if (allTags[i].className.includes("aa")) {
break;
}
selectedTags.push(allTags[i])
}
After that, you can iterate over selectedTags to do whatever you want with them, including storing variables.

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>

Getting the actual name of the class, and not the element within it?

To get elements using a class name, document.getElementsByClassName() can be used.
But is there a function in JavaScript to get the actual name of the class itself?
Example:
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].innerHTML;
<div class="myClass">Hello</div>
<div id="result"></div>
printResult will just print out "Hello". What if I want the result to print out the string "myClass" which is the actual class name?
I tried classElement[0].className.innerHTML but it returns undefined.
className is a property of the dom node containing the classes of the element.
You don't need to add innerHTML, which is another property of the dom node and returns/sets the html content of the corresponding element.
var classElement = document.getElementsByClassName('myClass');
var printResult = document.getElementById('result');
printResult.innerHTML = classElement[0].className;
<div class="myClass">Hello</div>
<div id="result"></div>

Get the last occurrence of an element [duplicate]

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>

getting text content of specific element

I'm trying to get element text content only ignoring element's descendants, for instance if you look at this HTML:
<p>hello <h1> World </H1> </p>
for element "P" the right output should be ONLY "hello ".
I have checked the function: "element.textContent" but this returns the textual content of a node and its descendants (in my example it will return "hello world").
Thanks,
Considering this HTML:
<div id="gettext">hello <p> not this </p> world?</div>
do you want to extract "hello" AND "world"? if yes, then:
var div = document.getElementById('gettext'), // get a reference to the element
children = [].slice.call(div.childNodes), // get all the child nodes
// and convert them to a real array
text = children.filter(function(node){
return node.nodeType === 3; // filter-out non-text nodes
})
.map(function( t ){
return t.nodeValue; // convert nodes to strings
});
console.log( text.join('') ); // text is an array of strings.
http://jsfiddle.net/U7dcw/
well behind it is an explanation
$("p").clone() //clone element
.children() //get all child elements
.remove() //remove all child elements
.end() //get back to the parent
.text();
The answer i have is the same provided in couple of other answer. However let me try and offer an explanation.
<p >hello<h1>World</h1> </p>
This line will be rendered as
hello World
If you look at this code it will be as follow
<p>hello</p>
<h1>World</h1>
<p></p>
With the <p> tag you do not necessarily need the closing </p> tag if the paragraph is followed by a element.
Check this article
Now you can select the content of the first p tag simply by using the following code
var p = document.getElementsByTagName('p');
console.log(p[0].textContent);
JS FIDDLE
You can use the childNodes property, i.e.:
var p = document.querySelector('p');
p.childNodes[0]; // => hello
jsFiddle
Change your html to
<p id="id1">hello <h1> World </h1> </p>
Use this script,
alert(document.getElementById("id1").firstChild.nodeValue);
Try to provide id for the element which you want to do some operation with that.
Below is the working example, it show output as "hello" as you expected.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showParagraph()
{
alert(document.getElementById('test').innerHTML);
}
</script>
</head>
<body>
<p id="test">hello <h1> World </H1> </p>
<input type="button" onclick="showParagraph()" value="show paragraph" />
</body>
</html>
Plain texts are considered as nodes named #text. You can use childNodes property of element p and check the nodeName property of each item in it. You can iterate over them and select just #text nodes.
The function below loops over all element in document and prints just #text items
function myFunction()
{
var txt="";
var c=document.body.childNodes;
for (i=0; i<c.length; i++)
{
if(c[i].nodeName == "#text")
txt=txt + c[i].nodeName + "<br>";
};
return txt;
}
EDIT:
As #VisioN said in comments, using nodeType is much more safer (for browser compatibility) and recommended.

Categories

Resources