Populate elements with class name using Javascript - javascript

I have some HTML which looks like this
<p>Latte: <span class="hot-drink"></span></p>
<p>Capuccino: <span class="hot-drink"></span></p>
<p>Coca Cola: <span class="cold-drink"></span></p>
<p>Water: <span class="cold-drink"></span></p>
<p>Iced tea: <span class="cold-drink"></span></p>
I would like to use javascript to populate all of the <span> elements with the class hot-drink applied to them with the variable hot-drink-status().
So far I have managed to do this to only one of the elements. The code I wrote looks like this:
var hot-drink = "Avaiable";
document.querySelectorAll('.hot-drink')[0].innerHTML = hot-drink;
I believe I need to change the [0] to something else. I have tried [i] but this does not work.
I know that querySelectorAll is working as it allows me to apply the script to any element. I am just unable to apply the script to all element.
The outcome I am looking for is the HTML to be rendered as below
<p>Latte: <span class="hot-drink">Available</span></p>
<p>Capuccino: <span class="hot-drink">Available</span></p>
<p>Coca Cola: <span class="cold-drink"></span></p>
<p>Water: <span class="cold-drink"></span></p>
<p>Iced tea: <span class="cold-drink"></span></p>
All elements with the class hot-drink are populated with the text "Available"

Try (do not use minus char in variable names - camel case instead)
var hotDrink = 'Available';
document.querySelectorAll('.hot-drink').forEach(el=> el.innerHTML= hotDrink)
<p>Latte: <span class="hot-drink"></span></p>
<p>Capuccino: <span class="hot-drink"></span></p>
<p>Coca Cola: <span class="cold-drink"></span></p>
<p>Water: <span class="cold-drink"></span></p>
<p>Iced tea: <span class="cold-drink"></span></p>

Related

How I can set focus on the element when I am setting it to content editable in Angular 6?

I am using the contentEditable attribute of Angular 6 for editing the content of the element (in the ngFor)
How I can set focus on a tag element when it's contentEditable attribute is true?
<div class="tag" *ngFor="let tag of tags">
<span [contentEditable]="underUpdateTagId==tag.id" [textContent]="tag.title
(input)="tag.title=$event.target.textContent">
</span>
<span *ngIf="underUpdateTagId!=tag.id" class="edit text-info" (click)="beforeEdit(tag)">
<i class="fas fa-pencil-alt"></i>
</span>
<span *ngIf="underUpdateTagId==tag.id" class="update text-success" (click)="editTag(tag)">
<i class="fas fa-check save"></i>
</span>
<span class="delete text-danger" (click)="delete(tag)">
<i class="fas fa-trash-alt"></i>
</span>
</div>
The user interface:
We can use ViewChildren to get a hold of all the spans, by placing a template reference, pick up the span that is selected and set the focus to the element.
So I suggest adding template reference and in your beforeEdit() pass the index of the tag (we get it from ngFor), so we can refer to it when we want to place the focus on the field:
<!-- add template reference in below span tag --->
<span [contentEditable]="underUpdateTagId==tag.id" ... #spans>
<!-- pass index as from ngFor iteration to beforeEdit() -->
<span *ngIf="underUpdateTagId!=tag.id" class="edit text-info" (click)="beforeEdit(tag, i)">
<!-- more code --->
In the component we refer to spans, the template reference. And when clicked upon specify that the span with the index passed should be focused:
#ViewChildren("spans") spans: QueryList<ElementRef>;
underUpdateTagId = null;
beforeEdit(tag, index) {
this.underUpdateTagId = tag.id;
// wait a tick
setTimeout(() => {
this.spans.toArray()[index].nativeElement.focus();
});
}
STACKBLITZ
PS, this sets the focus in the beginning, you might want it at the end, maybe this question can help you with it if that is the case: Use JavaScript to place cursor at end of text in text input element

Javascript select span on parent span and use wildcard

I want to use JavaScript to select the span element with a class of "price", but the selection has to be with the parent span with id "product-price-895". Additionally, I want to use a wildcard for the number part of the ID, so the selector has to be something like "#product-price-*"
<span id="product-price-895" data-price-amount="12.95" data-price-type="finalPrice" class="price-wrapper " >
<span class="price">€ 12,95</span>
</span>
You can use the following CSS selector: [id^=product-price] > .price.
The selector uses a child combinator which means it is only concerned with elements having the class of price that are an immediate child of any element whose id attribute begins with "product-price" (due to the attribute selector).
var spanEls = document.querySelectorAll('[id^=product-price] > .price');
spanEls.forEach(span => console.log(span.innerHTML));
<span id="product-price-1" data-price-amount="12.95" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">€ 12,95</span>
</span>
<span id="product-price-2" data-price-amount="5.50" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">€ 5,50</span>
</span>
<span id="product-price-3" data-price-amount="25.90" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">€ 25,90</span>
</span>
jQuery selectors can handle this fairly easily: https://api.jquery.com/category/selectors/
If you need to use vanilla JavaScript, you can use document.querySelector(): https://www.w3schools.com/jsref/met_document_queryselector.asp
If you want the child with the class "price" from the node with the id "product-price-895", you need to use the following css selector: #product-price-895 > .price.
In javascript I would use: document.querySelector('#product-price-895 > .price').
A more efficient way may be to use an attribute selector instead of the ID. You could search by document.querySelectorAll("[data-price-amount] > .price") or document.querySelectorAll("[data-price-type="finalPrice"] > .price"). This will also give you a bit more control and flexibility if the way your IDs get generated changes in the future.
To get all the spans with the class price where the parent starts with product-price- you could use an attribute starts with selector ^=
$("span[id^=product-price-] span.price")
document.querySelectorAll('span[id^=product-price-] span.price').forEach(x => console.log(x.innerHTML))
<span id="product-price-895" data-price-amount="12.95" data-price-type="finalPrice" class="price-wrapper ">
<span class="price">€ 12,95</span>
<span class="price">€ 13,95</span>
<span class="prices">€ 14,95</span>
<span class="price">€ 15,95</span>
<span><span class="price">€ 18,95</span></span>
</span>
<span class="price">€ 16,95</span>

How to click a button using html or java script which is declared as div

I am writing a powershell script to login to a website. I want to use the button.click functionality but I can't find the button's id. here is what I found by inspecting it.
<div tabindex="0" role="button" class="v-button v-widget default v-button-default">
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
</div>
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
<span class="v-button-caption">Login</span>
Thanks in advance
Given that you aren't sure which one is the one you want, you could just set up an event handler that will trigger for each and then interrogate it for something that can identify it.
// Get all the elements with a class of "v-button-caption" into an array
var buttons = Array.prototype.slice.call(document.querySelectorAll(".v-button-caption"));
// Loop over the array
buttons.forEach(function(btn){
// Set up a click event handler
btn.addEventListener("click", function(evt){
// Print out some identifying information about the clicked element
console.log("You clicked the element who's parent is: " + evt.target.parentElement.nodeName);
});
});
<div tabindex="0" role="button" class="v-button v-widget default v-button-default">
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
</div>
<span class="v-button-wrap">
<span class="v-button-caption">Login</span>
</span>
<span class="v-button-caption">Login</span>

Get index of an item from a group of identical items

Say I have a group of HTML tags that are identical, e.g.:
<div id="stuff">
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
</div>
I'm attaching an onclick event to the spans like so:
$(".foo").click(function() {
// stuff
});
In my onclick event, I want to get the index of the clicked element, so for example, if I clicked the 3rd span, I want the index to be 3. How would I do that? Normally, I'd iterate over $("#stuff") and compare the items to the clicked item, but in this case, they are identical.
Get the index by using:-
Indexes are zero based relative to its siblings. SO for the 3rd element you will get the index as 2.
$(".foo").click(function() {
alert($(this).index());
}
Read about .index()
Demo
HTML
<div id="stuff">
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
<span class="foo">Foo</span>
</div>
Jquery
$(document).ready(function(){
$('.foo').click(function(){
var x = $(this).index();
alert(x);
});
});
working Demo http://jsfiddle.net/cse_tushar/Jj72A/
You can write it like this:
$(".foo").click(function(){
alert(jQuery.inArray(this,$(".foo")));
});

wrapping div around string using jquery

How do i wrap a div class div class="includingVAT"></div> around the string text :incl. MwSt
<span id="VariantPrice_3181">
<span class="variantprice">
<span class="pricelabel">Preis </span>
240,00 (CHF)
</span>
incl. MwSt
<span id="plus-shipping">plus-shipping</span>
</span>
using jquery?
it needs to look like this:
<span id="VariantPrice_3181">
<span class="variantprice">
<span class="pricelabel">Preis </span>
240,00 (CHF)
</span>
<div class="includingVAT"> incl. MwSt</div>
<span id="plus-shipping">plus-shipping</span>
</span>
the string without span or div needs the div class includingVAT as there could be different language translations.
You can try this example here: DEMO
var text = $('#plus-shipping').map(function(){
return this.previousSibling.nodeValue
});
$('#plus-shipping').prepend('<div class="includingVAT">' + text[0] + '</div>');
$(".pricelabel").after('<div class="includingVAT">');
$(".plus-shipping").before('</div>');
This is awkward and error-prone. Is there any-way you can insert the whole div? Why does incl. MwSt exist only in the HTML?

Categories