I am looking to get a list of elements with a certain tag and if there is more than one loop through and remove the additional elements.
Currently I do:
if (document.getElementsByName("description")[0]) {
document.getElementsByName("description")[0].setAttribute("content", "My Description");
} else {
var meta = document.createElement('meta');
meta.name = "description";
meta.content = "My Description";
document.getElementsByTagName('head')[0].appendChild(meta);
}
But I want to remove anything that is after the first element? How would I do that?
you can do this:
[...document.getElementsByTagName('span')].slice(1).forEach(e=>e.parentNode.removeChild(e));
[...document.getElementsByTagName('div')].slice(1).forEach(e=>e.parentNode.removeChild(e));
First select all elements with the specific tag name. Transform it to an array (in this case with spread operator, you can also use [].slice.call(...). After that you can call slice on that array of elements and remove the first one out of this set. Loop through the elements and remove them. That's all :)
EDIT Solution for beginners:
var elements = document.getElementsByTagName('span');
for(var i=elements.length-1;i>0;i--)
elements[i].parentNode.removeChild(elements[i]);
If you want cut anything after description[0] in header, you can use that
'document.getElementsByTagName["head"].innerHTML = "";'
If you only want cut any description tags, use
var tags = document.getElementsByTagName('description');
for(i=0; i<tags.length; i++){
tags[i].remove();
}
Related
I'm trying to get all classes from one element, then add them to another element created dynamically. I was originally stuck on how to do this, but as I was typing out this question, I worked out a solution. However, it seems a bit verbose. Is there a way to do this same thing more efficiently, i.e. with fewer lines of code?
let classes = this.nextElementSibling.classList; // get classes from target element
classes += ''; // convert classlist object to string
let class_array = classes.split(' '); // convert string to array
const my_div = document.createElement('div'); // create a new div
for(i=0; i<class_array.length; i++) { // loop through array and add classes to the div
my_div.classList.add(class_array[i]);
}
Thanks in advance.
The className will give you a space-separated string of class names an element has. Just use that.
const my_div = document.createElement('div');
my_div.className = this.nextElementSibling.className;
I'm not exactly sure how to word this, but I am using Javascript to change text. I am using Javascript on the site Quizlet. As you can see, there are two columns: terms and definitions. As of now, the script changes both when I only want it to change the term list. Here's a video, too: https://drive.google.com/file/d/1ly3askpLQjzXeCMx9Mk9iVpSEXCw6i25/view
Works, but changes both:
var myClasses = document.getElementsByClassName("ProseMirror");
for (var i = 0; i < myClasses.length; i++) {
myClasses[i].innerHTML = "new content";
}
I tried this, but it didn't work:
var myClasses = document.getElementsByClassName("WordList");.document.getElementsByClassName("ProseMirror");
for (var i = 0; i < myClasses.length; i++) {
myClasses[i].innerHTML = "new content";
}
If you're trying to find a .ProseMirror element only when it's inside a .WordList element, you can use a CSS selector for that with querySelector:
const element = doucment.querySelector(".WordList .ProseMirror");
element.innerHTML = "new content";
That finds the first element with the class ProseMirror that's also inside an element with class WordList.
I don't think you want a list of matches, but if you did, you'd use querySelectorAll (which returns a NodeList of all matches) instead of querySelector (which returns the first matching element).
You can use document.querySelectorAll to get the elements with multiple classes.
document.querySelectorAll('.WordList.ProseMirror');
So lets say I want to hide a div or span with CSS of a particular class.
Is there anyway to do so for the first X number of instances, or better yet, do it for all except for the last one? I imagine this would require javascript.
pseudocode I am thinking would look like this
if divname.class = "XYZ" {
select all instances -1
execute code that inserts random programmatic id into each class
execute code that hides all ids except the last one
}
Am I on the right track? Or is there any easier/better way?
If you can use jQuery and its nice pseudo-selectors, you could do something like
$('.question-summary:not(:last)')
You can test on the SO homepage.
You could do something like this,
var class_div = document.getElementsByClassName("class_name");
var i =0;
for(i=0;i<class_div.length-1;i++){
//do whatever you want with class_div[n-1] elements.
}
I am not sure how you do this with jquery but this is one possible solution for javascript.
If you were using jQuery...
$('.class_name').hide().last().show();
Here ya go - http://jsfiddle.net/uUK6G/
Set all your divs to the same class. Then use jQuery to filter out the last one.
$('.myDiv').filter(':not(:last)').hide();
You can use the :last-child selector in CSS to do this.
http://www.w3schools.com/cssref/sel_last-child.asp
Is there anyway to do so for the first X number of instances, or
better yet, do it for all except for the last one? I imagine this
would require javascript.
You can try:
var elms = document.getElementsByClassName('XYZ'), total = elms.length;
for (var i = 0; i < total; i++){
elms[i].style.display = 'none';
}
In above loop, i will contain index of each element, you can put condition or rather range to specify which ones to delete. For example, if you wanted to hide all except for last one, you would modify it like:
for (var i = 0; i < total - 1; i++){
elms[i].style.display = 'none';
}
I am trying to add to all <object>'s on a page a snippet of html. I understand I can access elements by tag name and that I can change the element, but can I simple append to it instead?
In addition, I want to add it to the contents of each tag, not the end of the document. Which of these methods will work?
Assuming no library...
var elementToAppend = document.createElement(tagName); // Your tag name here
// Set attributes and properties on elementToAppend here with
// elementToAppend.attribute = value (eg elementToAppend.id = "some_id")
// You can then append child text and elements with DOM methods
// (createElement or createTextNode with appendChild)
// or with innerHTML (elementToAppend.innerHTML = "some html string")
var objects = document.getElementsByTagName('object');
for(var i = 0; i < objects.length; i++) {
elementToAppend = elementToAppend.cloneNode(true);
objects[i].appendChild(elementToAppend);
}
Using innerHTML or outerHTML as other answers have suggested will likely cause problems for whatever you've embedded with <object>.
appendChild is what you're looking for.
How can i populate multiple id tags simultaneously.
On my page i have id tags starting with "total_" phrase, like total_1, total_2 etc., is there a way by which i can populate each of them on a single click in javascript.
Should i use regex or parser.
Any help will be highly appreciated.
Thank you.
for(var i=1; true; i++){
var elm = document.getElementById("total_"+i);
if(elm == undefined){
break;
}
elm.innerHTML = "Some text here";
}
Using jQuery you can do the following:
$("div[id^='total_']").html("Some text Here");
If you know how many there are, you can simply loop through the numbers:
for (var i=1; i<=10; i++) {
document.getElementById('total_'+i).innerHTML = 'text';
}
If you are using jQuery, you can loop through all elements of a specific type, and look for the id. It's less efficient, but more flexible. It will work even if the numbers are not contiguous:
$('div').filter(this.id && this.id.substr(0,6) == 'total_').html('text');
(You can of course loop through elements without a library like jQuery, but then it's a bit more code...)