This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed last month.
i tried to change this text using getElementsByTagName() but it did not work i do not know what is the probleme
enter image description here
getElementsByTagName()
You should check the DOM documentation because you are misunderstanding what that function does, getElementsByTagName("s-button-text") isn't getting the element because thats not how it works.
This would work getElementsByClassName("s-button-text") or getElementsByTagName("span"), tag refers to the <span> in this case, and class refers to the class=" attribute.
I would highly recommend you don't use the second one as it will get other <span> elements in the page and not just the one you want.
As well, even if you replace that it will create an error, this is how to do what you want to do:
function change_content() {
let elements = document.getElementsByClassName('s-button-text');
for (let i=0; i<elements.length; i++) {
elements[i].innerHTML = "newText";
}
}
getElementsByTagName() returns an array of elements by tag name. You are trying to get an element by it's class so you need a different method. You can use querySelector() or querySelectorAll().
querySelector() is used to find a single element by a CSS selector.
querySelectorAll() is used to get a list of elements by a CSS selector.
This will find all elements with this class name and change the text of the first element returned:
document.querySelectorAll('.s-button-text')[0].textContent = 'New text';
Related
I am trying to select a DOM element that has these classes:
mq-editable-field mq-math-mode mq-field
I have tried using:
document.getElementsByClassName('mq-editable-field mq-math-mode mq-focused')
This is not working, is there another document function I should be using? I am using vanilla javascript.
Use a query selector:
document.querySelector('.mq-editable-field.mq-math-mode.mq-focused')
you can use querySelector and querySelectorAll for get multiple-element by classes
querySelector method : return the first element within the document which matches a specified CSS selector(s)
let firstElement= document.querySelector('.mq-editable-field.mq-math-mode.mq-focused');
querySelectorAll() method : method returns all the elements within the document which matches the specified CSS selector(s).
let elements = document.querySelectorAll('.mq-editable-field.mq-math-mode.mq-focused');
Suppose that I want to add a newly created paragraph (using document.createElement("p")) into an existing div (with class name "container") in one of my html files. Is there a way to do this by calling some methods?
Since there's a getElementById() method, I figured I would use a getElementByClassName() method too, but that doesn't exist; what exists is getElementsByClassName() instead. One way I can get around this is to just change my div to have an id rather than a class name, and use the getElementById() to add the paragraph into the div, but I wanted to know if there was some method that I could call that would help me retrieve a class element (rather than the elements within the class itself).
I've tried looking for this online, but what I've found are answers to "how to add class names to elements" instead, which is not what I want to know.
For one element, this will chose first in DOM order:
var p = document.createElement("p");
p.innerHTML = "p element";
document.querySelector(".container").appendChild(p);
<div class="container">container</div>
For all elements with chosen class:
[...document.querySelectorAll('.container')].forEach(el => {
var p = document.createElement("p");
p.innerHTML = "p element";
el.appendChild(p);
})
<div class="container">container</div>
<div class="container">container2</div>
HTML DOM elements' IDs have to be unique within a document - and so asking for an element by Id will return you just one element (or null if there isn't a matching element).
However a class name can be applied to multiple elements, so you would expect to get zero one or more elements when searching by class, hence the getElementsByClassName returns a collection.
So if you have a list of elements with the class name container, and you know your document (hopefully) only contains one element with that name, you can pick the first element returned by the getElementsByClassName - e.g. getElementsByClassName('container')[0]
Note - getElementsByClassName returns all elements to which the class has been directly applied, for the children of the element on which it is being called. I've interpreted your query as relating to the whole document in the context of your original question.
This question already has answers here:
For loop for HTMLCollection elements
(13 answers)
Closed 3 years ago.
I want to retrieve the content of all textarea elements inside a particular div. Here is how I tried to iterate over them
var ta = document.getElementById('parent').getElementsByTagName('textarea')
ta.forEach(element => {
console.log(element);
});
but I get
Uncaught TypeError: ta.forEach is not a function
at HTMLButtonElement.<anonymous> (details:512)
at HTMLButtonElement.dispatch (jquery.min.js:3)
at HTMLButtonElement.r.handle (jquery.min.js:3)
Is this the proper way to get all textarea elements inside a particular div?
I want to get the content of all of these textarea elements along with the name of the element. How can I do that?
getElementsByTagName returns HTMLCollection. It does not have the forEach method. Use the for loop as illsutrated in Element.getElementsByTagName().
var ta = document.getElementById('parent').getElementsByTagName('textarea');
for (let element of ta) {
console.log(element);
}
Use .querySelectorAll(), which allows for any valid CSS selector to be passed to it and it will return a collection of all matching elements. Then, loop over the results, but because IE doesn't support .forEach() on collections, you should convert it into a formal array before using .forEach().
And don't use .getElementsByTagName() (ever again).
// Get the textareas inside the div with an id of "target2"
let areas = document.querySelectorAll("#target2 textarea");
// Convert the collection into an array and loop over the array
Array.prototype.slice.call(areas).forEach(function(area){
console.log(area.textContent);
});
<div id="target">
<textarea>stuff</textarea>
</div>
<div id="target2">
<textarea>stuff2</textarea>
<textarea>stuff2a</textarea>
</div>
<div id="target3">
<textarea>stuff3</textarea>
</div>
If you are just trying to get the content of the input or textarea, I think you could use .value to capture that and print it to console.
something like:
for (i = 0; i < document.getElementById('parent').getElementsByTagName('textarea').length; i++) {
console.log(document.getElementById('parent').getElementsByTagName('textarea')[i].value)
}
editing since it HTML collection in fact does not work with .value
You want something like this?(Write text and click outside)
document.getElementsByTagName('textarea')[0].onchange = function(){ console.log(document.getElementsByTagName('textarea')[0].value);
}
<textarea></textarea>
This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
I'm trying to use
onmouseover="document.getElementsByClassName().style.background='color'"
to change the color of all divs with a given classname to another color when hovering over another page element.
Here is a jsfiddle -if anyone could give a few helpful pointers as to where I'm going wrong that would be great, I'm sure it's something really obvious that I'm missing. It worked with document.getElementById, but that only changed the color of the first div, not all of them.
Thanks :)
As the function name suggests getElementsByClassName returns a collection not just one object. So you need to loop through them and apply the color to it.
document.getElementsByClassName()
^_______
Plus your id part is invalid. Id cannot have spaces and also it shouldn't appear again on the page which is violated by:
<th id="colorswitcher A" onmouseover="document.getElementsByClassName('a').style.background='red'">a</th>
<th id="colorswitcher B" onmouseover="document.getElementsByClassName('a').style.background='blue'">b</th>
You can do it this way (You can look up what is a handler and try play yourself with it.), don't use inline attributes for handlers.
window.onload=function(){
var aColl = document.getElementsByClassName('a'); //Cache the collection here, so that even a new element added with the same class later we can avoid querying this again by using the cached collection.
var bColl = document.getElementsByClassName('b');
document.getElementById('A').addEventListener('mouseover', function(){
changeColor(aColl, 'red');
});
document.getElementById('B').addEventListener('mouseover', function(){
changeColor(bColl, 'blue');
});
}
function changeColor(coll, color){
for(var i=0, len=coll.length; i<len; i++)
{
coll[i].style["background-color"] = color;
}
}
Fiddle
If you are really trying to do it for some real work, then don't change the style attribute, instead define classes and add/remove classes on mouseover, mouseout events so that you get the power of css' cascading property.
This question already has answers here:
How to copy all the attributes of one element and apply them to another?
(12 answers)
Closed 3 years ago.
Is it possible transform one DOM element to another?
By jQuery or even by JavaScript.
I just to want for example:
get table > thead > tr > th's with all classes, attributes, properties and put it in table > body like as tr > td.
Or maybe is another way for that?
You have a couple options.
You can use jQuery's clone(), which will copy everything on/in the DOM node. Then use append() to attach the clone to whatever element you want it moved to. Then just remove the original node.
If you just want the attributes from the DOM node (classes, id, etc.) then you can use the attributes array that is present on all DOM nodes. You'd have to loop through each attribute and then set it on the new element individually though. I have yet to find a simple way to just copy everything over. In vanilla Javascript that would look something like this:
var originalELement = document.getElementById('original-element-id');
var newElement = document.createElement('div');
for (var i = 0; i < originalElement.attributes.length; i++) {
var attr = originalElement.attributes.item(i);
newElement.setAttribute(attr.nodeName, attr.nodeValue);
}
when you do element1.append(element2) element2 will move inside element1. append or appendChild. weird but true. append actually means "cut"