I am trying to do this:
Search for all the spans in my structure
Get the id value from each span
Update the parent with that text for test purposes
The reason for this work is that I am doing front-end customizations for an application and trying get some WAI-ARIA labelled-by values set on a parent element.
The problem is that many of the needed values come from an COTS application that I am working with/around. These needed input are not always set in a good sequence in the DOM.
I have been looking at a JS solution to get around this.
<div class="fluid-form-container">
<ul id="accordionGroup" class="Accordion" data-allow-multiple="">
<li class="fluid-form-group-container">
<h3 aria-labelledby="accordion1id">
<button aria-expanded="true" class="Accordion-trigger" aria-controls="sect1" id="accordion1id">
<span class="Accordion-title"><div class="fluid-form-title">
<div class="FormSection">
<span id="More_Info_Form_Section_Label">More Info</span>
</div>
</div>
</span>
</button>
</h3>
</li>
<li class="fluid-form-group-container">
<h3 aria-labelledby="accordion2id">
<button aria-expanded="true" class="Accordion-trigger" aria-controls="sect2" id="accordion2id">
<span class="Accordion-title"><div class="fluid-form-title">
<div class="FormSection">
<span id="Even_More_Info_Form_Section_Label">Even More Info</span>
</div>
</div>
</span>
</button>
</h3>
</li>
</div>
//My bad javaScript so far
var found_elements = [];
var outers = document.querySelectorAll('.FormSection');
for(var i=0; i<outers.length; i++) {
var elements_in_outer = outers[i].querySelectorAll("span");
var updateValue = elements_in_outer.getAttr("id");
outers[i].closest("h3").innerHTML = updateValue;
}
The expect results:
- parent tag innerHTML set to the id value of each span in the structure
Actual results:
- I'm getting errors because I am not sure what I need to use to get that id from each span found
querySelectorAll() returns a NodeList , so elements_in_outer.getAttr("id") won't work and should be replaced with querySelector()
there is no getAttr, use getAttribute
( i replaced your for with a forEach )
var found_elements = [];
var outers = document.querySelectorAll('.FormSection').forEach(div => {
var elements_in_outer = div.querySelector("span");
var updateValue = elements_in_outer.getAttribute("id");
div.closest("h3").innerHTML = updateValue;
});
<div class="fluid-form-container">
<ul id="accordionGroup" class="Accordion" data-allow-multiple="">
<li class="fluid-form-group-container">
<h3 aria-labelledby="accordion1id">
<button aria-expanded="true" class="Accordion-trigger" aria-controls="sect1" id="accordion1id">
<span class="Accordion-title"><div class="fluid-form-title">
<div class="FormSection">
<span id="More_Info_Form_Section_Label">More Info</span>
</div>
</div>
</span>
</button>
</h3>
</li>
<li class="fluid-form-group-container">
<h3 aria-labelledby="accordion2id">
<button aria-expanded="true" class="Accordion-trigger" aria-controls="sect2" id="accordion2id">
<span class="Accordion-title"><div class="fluid-form-title">
<div class="FormSection">
<span id="Even_More_Info_Form_Section_Label">Even More Info</span>
</div>
</div>
</span>
</button>
</h3>
</li>
</div>
If you know beforehand that you will only use the span elements that have an id, then use [id] in the querySelectorAll selector likewise
document.querySelectorAll('span[id]')
If you will use that as an array, then you need
[... document.querySelectorAll('span[id]')]
Assigning the new value would be something like this:
[... document.querySelectorAll('span[id]')].forEach(s => s.closest("h3").innerHTML = s.id)
Related
I want to copy values from the elements declared in jsp and spray them on the screen.
sampe.html
<div class="island_a">
<div class="island_b">
<ul class="island_c">
<li class="aaaaaa">
<span class="fitCenter">
<p class="city">[seoul shop]</p>
<p class="store">a_center</p>
</span>
</li>
<li class=bbbbbb">
<span class="fitCenter">
<p class="city">[incheon]</p>
<p class="store">b_center</p>
</span>
</li>
<li class="cccccc">
<span class="fitCenter">
<p class="city">[china]</p>
<p class="store">c_center</p>
</span>
</li>
<li class="dddddd">
<span class="fitCenter">
<p class="city">[USA]</p>
<p class="store">d_center</p>
</span>
</li>
The sample.html is written like the code above.
I want is to copy aaaaaa, bbbbbb, cccccc, dddddddd from li class and show them on the screen.
I tried code 1
var listElements = $(".island_a .island_b .island_c .aaaaaa").clone().wrapAll('<li>');
var listElements = $(".island_a .island_b .island_c .bbbbbb").clone().wrapAll('<li>');
var itemHTML = listElements.parent().html();
$(".island_a .island_b .island_c").html(itemHTML);
Only aaaaaa values of the li class are imported into the screen.
I tried code 2
var itemList = [];
var $listElements1 = $(".fitWhereWrap .fitWhere .aaaaaa").clone().wrapAll('<li>').push();
var $listElements2 = $(".fitWhereWrap .fitWhere .bbbbbb").clone().wrapAll('<li>').push();
$(".fitWhereWrap .fitWhere").html(itemList);
The above code does not work.
Please save me.
Please help me
$(() => {
$('.fitCenter').each((index, item) => {
$('body').append(item);
})
});
I'm trying to only show class="important" whenever certain text/products like 'KR-KJSC-MICROBIT' and 'KR-KJSC-D' are on the page. When those texts are not on the page then this element should be hidden. Can anyone please assist me with this?
<div class="important">SHOW IF CERTAIN PRODUCTS ARE IN THE CART/THANK YOU PAGE</div>
<div class="cart-line-product-info>
<span class="cart-product-code">
<a class="product-code">Code: KR0KJSC-MICROBIT</a>
</span>
</div>
<div class="cart-line-product-info>
<span class="cart-product-code">
<a class="product-code">Code: KR-KJSC-D</a>
</span>
</div>
You can set a variable with the specific words you want to match.
Get html elements.
Iterates throught the product codes (anchors).
If words array includes the textContent of an anchor element, then display the importants elements:
let words = ['KR0KJSC-MICROBIT', 'KR-KJSC-D']
let anchors = document.querySelectorAll(".product-code")
let importants = document.querySelectorAll(".important");
for(let i = 0; i < anchors.length; i++){
if(words.includes(anchors[i].textContent.replace('Code: ', ''))){
importants.forEach(x => x.style.display = 'block')
} else {
importants.forEach(x => x.style.display = 'none')
}
}
<div class="important">SHOW IF CERTAIN PRODUCTS ARE IN THE CART/THANK YOU PAGE</div>
<div class="cart-line-product-info">
<span class="cart-product-code">
<a class="product-code">Code: KR0KJSC-MICROBIT</a>
</span>
</div>
<div class="cart-line-product-info">
<span class="cart-product-code">
<a class="product-code">Code: KR-KJSC-D</a>
</span>
</div>
Here is a way to do it. Not really the best solution but will work if you add the js script at end of page.
const codeElements = document.querySelectorAll(".product-code");
let codes = []
codeElements.forEach( element => codes.push(element.innerHTML))
if(!codes.includes("Code: KR-KJSC-D")) {
document.querySelector(".important").style.display = "none"
}
<div class="important">SHOW IF CERTAIN PRODUCTS ARE IN THE CART/THANK YOU PAGE</div>
<div class="cart-line-product-info>
<span class="cart-product-code">
<a class="product-code">Code: KR0KJSC-MICROBIT</a>
</span>
</div>
<div class="cart-line-product-info>
<span class="cart-product-code">
<a class="product-code">Code: KR-KJSC-D</a>
</span>
</div>
let pageSource = document.documentElement.innerHTML
// regex match for target strings against page source
if(pageSource.match(/KR0KJSC-MICROBIT|KR-KJSC-D/g)){
$('.important').show()
}
So I have ul's on my webpage similar to the one below and I'm trying to loop through each of them to grab a span within the li. Below is an example of how it appears in my HTML:
<ul id="item-NineAM" class="list-group">
<li class="list-group-item w-100 border-dark past">
<span class="badge badge-dark" id="item-time">09:15 AM</span>
<p class="m-1 w-75 item-text">fsda</p>
<button class="btn btn-danger" id="trashCan"><span class="oi oi-trash"></span></button></li>
</ul>
I've set up an interval to grab the span with id #item-time and pass it into my audit function
const listGroup = $(".card .list-group li #item-time");
$.each(listGroup, function(i, itemSpan){
console.log(itemSpan)
auditItem(itemSpan)
})
I've verified in the console that the span is passed into function but I cannot seem to grab the text of it.
<span class="badge badge-dark" id="item-time">09:15 AM</span>
I need to grab the time that's inside of the span. My console tells me it's an object. Any ideas? I've tried .text() and .innerHTML but no luck.
Thanks!
The jquery selector you're assigning to listGroup should be pretty general, so you wouldn't include an id as you'd only get one match.
It looks like you're misusing id. Remember, you can only have a single instance of id and it should only be used to indicate uniqueness. Instead you want item-time to be a class since you can have several instances of classes.
I've corrected some others in your html as well.
const listGroup = $(".list-group li span.item-time");
$.each(listGroup, function(){
console.log($(this).text())
//auditItem(itemSpan)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="list-group item-NineAM">
<li class="list-group-item w-100 border-dark past">
<span class="badge badge-dark item-time">09:15 AM</span>
<p class="m-1 w-75 item-text">fsda</p>
<button class="btn btn-danger trashCan">
<span class="oi oi-trash"></span>
</button>
</li>
</ul>
Simply put, trying to push simple answer values to a jquery array.
HTML
<div class="answer-A">
<a href="#question2" value="A">
<p style="color: white;">THOMAS EDISON</p>
</a>
</div>
<div class="answer-B">
<a href="#question2" value="B">
<p style="color: white;">ALBERT EINSTEIN</p>
</a>
</div>
<div class="answer-C">
<a href="#question2" value="C">
<p style="color: white;">NELSON MANDELA</p>
</a>
</div>
Jquery
var finalAnswers = [''];
$(document).ready(function () {
$('.answer-A').finalAnswers.push();
console.log(finalAnswers);
});
Probably shouldn't be using value - there's probably a much easier way?
If I understood correctly your question, I created this fiddle with an approach to accomplish your task:
https://jsfiddle.net/mrlew/hvr9ysq6/
html:
<div class="answer-A">
<a href="#" data-value="A">
<p style="color: white;">THOMAS EDISON</p>
</a>
</div>
<div class="answer-B">
<a href="#" data-value="B">
<p style="color: white;">ALBERT EINSTEIN</p>
</a>
</div>
<div class="answer-C">
<a href="#" data-value="C">
<p style="color: white;">NELSON MANDELA</p>
</a>
</div>
js:
var finalAnswers = [];
$(document).ready(function () {
$("a[data-value]").on("click", function(e) {
var value = $(this).attr('data-value');
finalAnswers.push(value);
alert("Answers so far: " + finalAnswers.join(","));
e.preventDefault();
});
});
Here is example for your comment about how you want to push the value that user click.
var finalAnswers = [];
$(".answer-A, .answer-B, answer-C").click(function(){
var value = $(this).children("a").attr("value");
finalAnswers.push(value)
});
Use a selector that matches divs with class that start with answer and their anchor children
div[class^="answer-"] a
Iterate through these elements and get their value attribute. Like this:
var finalAnswers = [''];
$(document).ready(function () {
$('div[class^="answer-"] a').each(function(i,v){
finalAnswers.push($(v).attr("value"));
});
console.log(finalAnswers);
});
Fiddle
https://jsfiddle.net/1gmn1w1b/
I'd like to get the data-league values of all of those divs, and put them into an array.
What I want to do: Get all those values, save them, and then loop through them, and call a .click on those divs.
I don't know if there's an easier way to do this.
I guess it also has to loop through the divs where ID=128, and find the data-league values, right?
Honestly I'm completely stuck, so any help whatsoever would be appriciated.
Thank you.
Extra info: Basically the end result being, on click of a button, all those 'thumbnails' should open in a new tab. All tabs being different streams.
(See image)
In the example you provided the same id (128) has been used multiple times. This is not allowed. Iterating through the ids will not work.
This means you have to look for another possibility. Getting all div elements with a certain class would be possible, like in the example:
var divs = document.getElementsByClassName('videoPanel');
Now you can iterate through this collection, extract the values for the attribute data-league and save them somewhere, for example in an array:
var dataLeagueValues = [];
for (var i = 0; i < divs.length; i++) {
dataLeagueValues.push(divs[i].getAttribute('data-league'));
}
Now you have all values in the array dataLeagueValues. You can use them further in your script.
You could use the $('[attribute]') selector to select elements with data-league, you can then use .each(); to loop them.
The following example triggers a click on every element with a data-league attribute:
$('[data-league]').each(function() {
$(this).trigger('click');
});
You could also make the selector more specific to only match these elements by their shared class name videoPanel e.g.
$('.videoPanel[data-league]').each(...);
Will target all elements with a class of videoPanel and an attribute data-league
To match what you need the full example would be:
var leagues = [];
$('.videoPanel[data-league]').each(function() {
leagues.push($(this).attr('data-league'));
});
Following code snippet will your insert all data-league into an array.
var leagues=[];
$('.vedioPnnel').each(function() {
var league = $(this).data('league');
leagues.push(league);
});
console.log(leagues);
I propose to use the javascript forEach function like in the folowing snippet.
Alternatively you can use:
document.querySelectorAll('[id="127"]');
or
document.querySelectorAll('[data-league]')
function getAllDataLeague()
{
var leagues = [];
Array.prototype.forEach.call(document.getElementsByTagName('div'), function (value, index, traversed) {
var attrVal = value.getAttribute('data-league');
if (attrVal) {
leagues.push({'obj': value, 'data-league': attrVal});
}
});
return leagues;
}
var eleFound = getAllDataLeague();
// print result in the html body
document.body.innerHTML += '<p>To access elements: eleFound[index]["data-league"]</p>';
document.body.innerHTML += '<p>To trigger the click event: eleFound[index]["obj"].click()</p>';
document.body.innerHTML += '<p>Elements found:</p>';
for (var i = 0; i < eleFound.length; i++) {
document.body.innerHTML += '<div>data-league:' + eleFound[i]["data-league"] + '</div>';
}
<div class="game-listing-group">
<div class="bold game-listing-name">CS:GO</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=m0e_tv" data-league="1284">
<div class="video-thumbnail-con hidden-xs hidden-sm">
<img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_m0e_tv-320x180.jpg">
</div>
<div class="videoPanelTextBg">
<p class="indexVideoPanelTitle">Dragon lore giveaway NOW</p>
<span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
</div>
<div class="indexVideoPanelGoldCount video-upcoming">
<i class="glyphicon glyphicon-time"></i>
<span class="vu-league-start"></span>
</div>
</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=freakazoid_tv" data-league="1296">
<div class="video-thumbnail-con hidden-xs hidden-sm videoPanelTextBgActive">
<img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_freakazoid_tv-320x180.jpg">
</div>
<div class="videoPanelTextBg">
<p class="indexVideoPanelTitle">BIRTHDAY IN 24HOURS! #c9freakazoid</p>
<span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
</div>
<div class="indexVideoPanelGoldCount video-upcoming">
<i class="glyphicon glyphicon-time"></i>
<span class="vu-league-start"></span>
</div>
</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=gripex90" data-league="1301">
<div class="video-thumbnail-con hidden-xs hidden-sm">
<img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_gripex90-320x180.jpg">
</div>
<div class="videoPanelTextBg">
<p class="indexVideoPanelTitle">Gripex - Most dedicated Lee sin! Top 50 Challenger</p>
<span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
</div>
<div class="indexVideoPanelGoldCount video-upcoming">
<i class="glyphicon glyphicon-time"></i>
<span class="vu-league-start"></span>
</div>
</div><div class="videoPanel vu-channel-tab" id="127" data-channel="https://www-cdn.jtvnw.net/swflibs/TwitchPlayer.swf?channel=phantoml0rd" data-league="1346">
<div class="video-thumbnail-con hidden-xs hidden-sm">
<img class="img-responsive video-thumbnail full-width" src="https://static-cdn.jtvnw.net/previews-ttv/live_user_phantoml0rd-320x180.jpg">
</div>
<div class="videoPanelTextBg">
<p class="indexVideoPanelTitle">Level 400 Gambler LOL - Cycled over 3,000,000 in s</p>
<span class="indexVideoPanelGoldCount vu-league-gold pull-right" style="display: none;"></span>
</div>
<div class="indexVideoPanelGoldCount video-upcoming">
<i class="glyphicon glyphicon-time"></i>
<span class="vu-league-start"></span>
</div>
</div></div>