How to iterate over all textarea elements inside a div [duplicate] - javascript

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>

Related

how can i change this span text using JS [duplicate]

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';

Append text to existing span tag [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
I have the following HTML
<div class="card-text" data-test-info-type="price">
<div class="price-section price-section--withoutTax ">
<span data-product-price-without-tax="" class="price price--withoutTax">$20.00</span>
</div>
</div>
I'm trying to append the following text to the $20.00 Prices include taxes
So the end result would be $20.00 Prices include taxes
However I'm hitting a brick wall trying to achieve this I have tried the following:
var span = document.getElementsByClassName("price price--withoutTax");
var txt = document.createTextNode("Prices include taxes");
span.innerText = txt.textContent;
Yet it remained as $20.00
I then tried
document.getElementsByClassName('price price--withoutTax').innerHTML = "hello";
Again same result stayed as $20.00
Can someone shed some light on how I go about appending additional text to a span tag?
The thing is that document.getElementsByClassName return an HTML collection, or a bunch of elements in 'array' sort of structure. So that means, this:
var span = document.getElementsByClassName("price price--withoutTax");
span.innerText = ...;
Will not work because span isn't one element, it's a list. Even if you have one element with the class name, it will return you a list of just one element. If you want only the first element, or are only using the first element, do:
var span = document.getElementsByClassName("price price--withoutTax")[0];
Notice the [0]. This access the first element of the 'array' like return value of document.getElementByClassName, giving you the first element with the given class name. If you want to get the value of more than one of the elements, you can loop over it and do whatever to each element.

Split Javascript String into an array of strings by looking for keyword

Working on a personal project that parses through an HTML document inserted into a textarea and produces a new HTML document with added modifications.
What my issue is, I want split certain divs with class="dog" into an array with each element in the array being divs of class of dog.
HTML:
<div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
<div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
JS Idea:
dogs[x] = intext.slice(intext.indexOf('<div class="dog"'), /*next instance of dog*/);
Array would look like:
dog[0] = <div class="dog">
<div class="mouth"></div>
<dig class="legs"></dig>
</div>
I tried using .indexOf('<div class="dog"') to try and create an array of indexes so I can use it to split the main string but no luck.
Any ideas of how I can accomplish this?
There exists a feature called query selectors. With these you can select all elements with a certain class, or all elements of a certain tag, ...
This will suit your specific need: querySelectorAll
the regular querySelector() will only select the first element which is why you need to use querySelectorAll(). It will give you a list of elements with which you can continue working.
Example:
var dogDivs = document.querySelectorAll(".dog");
EDIT:
As you have just now mentioned it is text from a textarea, as suggested by an other answer you could first load it into your DOM structure. Preferrably in a hidden element so that the user is unaware of it.
First you need to load the content onto the DOM:
document.createElement("div").innerHtml(intext);
Then you can find the dog elements as the other answers have suggested:
var elements = document.getElementsByClassName('dog');
Be careful when loading user inputted data into the DOM, this can open doors to being hacked.
You should never parse html as a string. Use a DOMParser to convert it to a document and then you can use all the standard methods
var parser = new DOMParser();
var doc = parser.parseFromString(stringContainingHTMLSource, "Text Area Content");
divs = doc.getElementsBYTagName("div");
Then you can use the built in Document interface. For your specific case, here are a few methods you can use.
get an array of all divs:
document.getElementsByTagName("div");
get an array of all divs with a specific class:
document.getElementsByClassName("dog");
get an array of all divs with a specific id:
document.getElementById("id");
The full list of very useful methods can be found on MDN.
var elements = document.getElementsByClassName('dog');
var arr = [].slice.call(elements);
arr is the array you want to have. elements is HTMLCollection, and doesn't have array prototype methods.
You can try getting all elements with class dog:
var dogs = document.getElementsByClassName("dog");
But this will return all elements with class dog. Then you can try this snippet:
function splitByClass(tag, cl) {
var els = document.getElementsByClassName(cl);
var res = [];
for (i = 0; i < els.length; i++) {
if (els[i].tagName.toLowerCase() == tag.toLowerCase()) {
res.push(els[i]);
}
}
return res;
}
console.log(splitByClass("div","dog"));
If you want to parse it as text without converting it into a DOM object which could potentially error if there is any mistakes with the users input formatting. Try a solution like the one I suggested here for searching XML code:
https://stackoverflow.com/a/34299948/1011603
This will let you search for a start tag, eg and an end tag, you just need to tweak the .substring sizing for the size of your search start/end tag eg the div.
For the thing you are doing you don't use the slice tool. This would be used for a String and you don't use the index of because that's just searching a string for a specific part.
What you do want to use is the
document.querySelectorAll(".example");
You will put the class dog where the .example is as the same format.
This command will return an array of all of the possible divs
If you need any more help, go to this link
http://www.w3schools.com/jsref/met_document_queryselectorall.asp

how to remove a div using javascript [duplicate]

This question already has answers here:
Remove DIV tag using Javascript or Jquery
(5 answers)
Closed 8 years ago.
so I'm trying to remove a div using javascript, the div I'm trying to remove:
<div class="popover fade left in" style="top: -76.5px; left: -404px; display: block;">
The code I am using to try to remove it:
Close
Am I doing anything wrong?
If you're using the remove jQuery function, you need to call it on a jQuery object. getElementByClassName returns a plain DOM element. Use the jQuery selector $ to select the element and wrap it in a jQuery object, and then call .remove on it:
$('.popover').remove();
If you're using the plain JavaScript .remove(), you need to call it on a single DOM element, but getElementsByClassName returns a collection. Try this:
getElementsByClassName('popover')[0].remove()
Try using this code:
HTML
Close
Javascript
removePopovers = function () {
var popovers = document.querySelectorAll('.popover');
for (var i = 0; i < popovers.length; i++) {
popovers[i].outerHTML= '';
}
}
This selects all elements with the popover class and sets theirouterHTML to nothing, which removes the divs.
JSFiddle

Is it possible transform one DOM element to another? Or copy all attributes from it? [duplicate]

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"

Categories

Resources