Catching an element by class name and adding innerHTML to it - javascript

I have had trouble getting hold of my elements class name. Now that I finally managed to do so, I do not seem to be able to add innerHTML to it.
I am adding an quote within an existing element. This is how I managed to get the class name as no other way of getElementsByClassName did not work:
var elements = document.getElementsByClassName('name-of-element');
for(var i=0; i<elements.length; i++) {
}
I tried combining the two scripts I have like so:
var elements = document.getElementsByClassName('name-of-element');
for(var i=0; i<elements.length; i++) {
elements.innerHTML = 'the change I am trying to make';
}
I tried changing the "elements" of "elements.innerHTML" but have not figured out anything that would work.
Any help is greatly appreciated!

You need to use elements[i] in your loop, it's not working because you're trying to change the innerhtml of the html collection rather than of the individual elements inside it.
Remember that getElementsByClassName (plural elements) returns an array-like object called a html collection.
var elements = document.getElementsByClassName('name-of-element');
for(var i=0; i<elements.length; i++) {
elements[i].innerHTML = 'the change I am trying to make';
}
<div class='name-of-element'></div>
<div class='name-of-element'></div>
<div class='name-of-element'></div>
<div class='name-of-element'></div>
<div class='name-of-element'></div>

Related

select html element by its full html tag - JS

I am looking for a way to be able to select an HTML element by its tag, like:
document.querySelector("<div id='myDiv'\>hello world</div\>")
//instead of: document.querySelector("#myDiv")
However, this code returns an error. The code should return the HTML element.
Does anybody know a way to achieve this? (vanilla JS preferred)
It seems a bit odd that you wouldn't want to select element via ID. But regardless one way of selecting the element in your example would be to look for its innerHTML.
e.g
var div = document.getElementsByTagName('div');
for (var i=0;i<div.length;i++){
console.log(div[i].innerHTML)
if(div [i].innerHTML == 'hello world'){
var element = div[i].parentElement
console.log(element)
break;
}
}
You could use outerHTML to search for it, however this only works if the element has a parent element.
var els = Array.from(document.querySelector('body *')); //this selects all elements in the body
var el;
for(var i = 0; i < els.length; i++) {
if(els.outerHTML === "<div id='myDiv'\>hello world</div\>") {
el = els[i];
}
}
//Use the el variable for your element

Why wont my onclick not remove any of my classes?

I have a huge problem here.
I can't get my onclick to work as I want .. So I hope someone here can help me.
#NiceToKnow
<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="nice"></div>
<div id="cards" class="video"></div>
I want it to display: none; every of my class="nice", so you only can see class="video", but nothing happens at all.
You are selecting the elements of the class not the class itself. So you will have to loop through the elements as javascript can only edit what is in the DOM not the CSS classes that effect your elements. So getElementsByClassName returns an array of nodes in which we must loop through and hide each one. Click runsnippet below to see this work
function changeNice(){
//ASSIGN ELEMENTS TO ARRAY
elementsofClass=document.getElementsByClassName('nice');
for(i=0; i<elementsofClass.length; i++){
//HIDE SELECTED ELEMENT
elementsofClass[i].style.display='none';
}}
#NiceToKnow
<div id="cards1" class="nice">TEST 1</div>
<div id="cards2" class="nice">TEST 2</div>
<div id="cards3" class="nice">TEST 3</div>
<div id="cards4" class="video">I don't HIDE</div>
Also don't use duplicate ID. This will cause errors later when trying to select your elements.
The getElementsByClassName will return an array, so we need to iterate through the array and hide one by one.
So it is better to declare a function and define the logic inside that. Please see the example below.
window.hideAllniceClass = function () {
var elems = document.getElementsByClassName('nice');
for (var i = 0; i != elems.length; ++i) {
elems[i].style.display = "none"; // hidden has to be a string
}
}
#NiceToKnow
<div id="cards1" class="nice">Test Content</div>
<div id="cards2" class="nice">Test Content</div>
<div id="cards3" class="nice">Test Content</div>
<div id="cards4" class="video">Test Video Content</div>
DEMO
Change your code to something like that:
var elems = document.getElementsByClassName('nice');
for(var i = 0; i < elems.length; i++) {
elems[i].style.display = 'none'
}
You have to iterate on the results returned by getElementsByClassName.
jsfiddle
You can create a loop that will loop through all the nice elements and then display none like this: https://jsfiddle.net/7vf9pz8u/
<script>
function hide(){
for(ct=0; ct < 3; ct++){
document.getElementsByClassName('nice')[ct].style.display='none'
}
}
</script>
getElementsByClassName returns array of all the match elements so you will have to provide index or loop through all of them to change their property.
Change your code to this
document.getElementsByClassName('nice')[0].style.display='none'
//For every element
var e = document.getElementsByClassName('nice');
for (i = 0; i < e.length; i++) {
e[i].style.display = "none";
}
As your divs do not have unique names they are in an array cards[].
So to access a particular div you need to reference the the array to that particular div. The quoted solution should work.

Get subclass of document.getElementsByClassName

So, I have this html code:
<div class='class1' id='example'>
<span class='class2'>Some text</span>
<span class='class3'>Some text 2</span>
</div>
I want to get every class1 and then add an event listener (click) on class2 and class3 (and I need that id to get some info from a PHP file). I tried something like this:
var yes = document.getElementsByClassName('class1');
for (var i=0 ; i<yes.length;i++)
yes[i].getElementsByClassName('class2').addEventListener('click',redirectfunction,false);
It's not working. What can I do?!
You are probably better to use querySelectorAll as it has wider support than getElementsByClassName (IE 8+) and you can get the elements in one go:
var yes = document.querySelectorAll('.class1 > .class2, .class1 > .class3');
querySelectorAll returns a static NodeList, so iterate over the returned object to access the members.
However, be prepared to provide a fallback for older browsers.
At first getsElementsByClassName should be getElementsByClassName (if not a typo) and then yes[i].getElementsByClassName('class2') returns a HTMLCollection of found elements and you are using this:
yes[i].getElementsByClassName('class2')
.addEventListener('click',redirectfunction,false);
So, you are trying to add an event listener on a collection. You may use another loop if there are multiple elements or just use something like this:
yes[i].getElementsByClassName('class2')[0]
.addEventListener('click',redirectfunction,false);
Update: (Example)
var els = document.querySelectorAll('div.class1');
for(var i =0, l=els.length; i<l; i++) {
var cls = els[i].querySelectorAll('span[class^=class]');
for(var x =0, n=cls.length; x<n; x++) {
cls[x].addEventListener('click', function(e) {
redirectfunction.call(this, e, this.parentNode.id);
}, false);
}
}
function redirectfunction(e, id) {
alert('This is id: ' + id);
}

How to remove all HTML tag by using the loop with Javascript

<div id='images'><img id='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
How to remove all <div> with the loop with Javascript?
Here is my code:
var value = document.getElementsByTagName("images");
for (var i = 0; i < value.length; i++) {
$(value[i]).remove();
}
You can only use same id value once per page. Change it to class, i.e. images
You will then have multiple div with class images and will be able to easily remove the spinners like this:
$(".images").remove();
If you have a lot of spinners, just wrap them with a div and remove the div. Something like this:
HTML:
<div id="jedi-wrapper">
<div class="images">
...
</div>
</div>
jQuery:
$("#jedi-wrapper").remove();
From the image, it looks like you are loading some values using AJAX. Why don't you remove the image on success?
Hope that helps
Seem like you want to remove all div with id images, but id is unique, you can use class instead:
<div class='images'><img class='center_loadingImage' align='middle' src='loading.gif' alt='Loading Image'></div>
then you can do:
$('.images').remove()
With your code you can do this:
document.getElementsByClassName("images").remove();
or more like jQuery:
$('.images').remove();
Althoug you can try this too:
var value = document.getElementsByClassName("images");
for (var i = 0; i < value.length; i++) {
$(value).eq(i).remove();
} //-------^^^^^^--------------you can make use of `.eq()` here
What your issue is there is no tag name like 'images' as your var suggests.
var value = document.getElementsByTagName("images");
images is the class name so you can use this:
document.getElementsByClassName("images")
Get element by ID, there's nothing with document.getElementsByTagName("images")
var c = document.getElementById('images');
var i, item = c.childNodes;
for (i = item.length; i--;) {
c.removeChild(item[i]);
}
You should probably be using class="images" instead of id="images" if that element is being rendered multiple times.
But to do this in a loop with raw javascript, you will need to first get the elements, convert them to an array, and then remove them in a loop.
var imageElements = doc.getElementsByClassName('images'),
images = Array.prototype.slice.call(imageElements);
for (var i = 0, l = images.length; i < l; i++) {
images[i].remove();
}
Notice that I don't just loop through imageElements... That's because getElementsBy...() returns a live list, so as soon as you remove() one of them, the list will be mutated and you will start running into undefined elements and javascript errors. To solve this, simply convert the live list to an array with Array.prototype.slice.call() and then loop through that array, removing the elements from the page.

Using Javascript, what is the method to get an element, based on the text between the opening and closing tags?

I'm a beginner, and couldn't find the answer after searching.
In my example, I'm looking for an
some text here
I'd want to find this particular element, so I can do stuff with it.
Edit: The only thing I know that's unique about the element for sure, is the text "some text here", that's why I want to find it based on that.
Put id on the element:
<a href="bla" onclick="dah" id='myEl'>some text here</a>
From javascript:
var myEl = document.getElementById('myEl') // gives the element
You can also use psuedo selector :contains, with the jQuery library.
Example 2
$('div:contains("test")').css('background-color', 'red');​
http://jsfiddle.net/9z5du/
Example 2
<script>
$("div:contains('John')").css("text-decoration", "underline");
</script>
If you know that the element is a link, you can first call getElementsByTagName [docs] to narrow down your search:
var elements = document.getElementsByTagName('a');
Then you have to iterate over the elements and test which one contains the next you are looking for:
var element = null;
for(var i = 0, l = elements.length; i < l; i++) {
if(elements[i].innerHTML === 'some text here') {
// found the element
element = elements[i];
break;
}
}
if(element) {
// found the element, lets do something awesome with it
}
There are multiple ways to get the content of an element, using Node#innerText (IE) or Node#textContent (W3C) is another option. You might have to trim the text first before you compare it.
If the HTML is as shown in your post,
if(elements[i].firstChild || elements[i].firstChild.nodeValue)
is even more elegant.
The MDN documentation about the DOM might be helpful.
If you can modify the HTML then adding an ID and using getElementById would be the better option.
Try this
function getit()
{
var elems = document.getElementsByTagName('a');
for(var i=0; i<elems.length; i++)
{
var text = elems[i].childNodes[0] != null ? elems[i].childNodes[0].nodeValue : '';
if(text == "some text here")
doSomethingWith(elems[i]);
}
}

Categories

Resources