How to put a <script> inside a <script>? - javascript

JS noob here.
I'm not sure if this if I'm doing this correctly but I'm trying to run a script "within" another script.
<script type="text/discourse-plugin" version="0.8">
api.decorateWidget('post:after', helper => {
let post = helper.getModel();
if (post.get('post_number') % 3 === 0) { // after every 3 posts
return helper.rawHtml(`
<div class="lead_static_wrapper"><p>Label</p>
<div class="proper-ad-unit">
<div id="pr-ad-nr_main_1">
propertag.cmd.push(function() { proper_display('nr_main_1'); });
</div>
</div>
</div>
`);
}
});
</script>
I need this part to run but it just shows as text when live, and doesn't seem to be running.
propertag.cmd.push(function() { proper_display('nr_main_1'); });
This doesn't seem to be the working:
<script type="text/discourse-plugin" version="0.8">
api.decorateWidget('post:after', helper => {
let post = helper.getModel();
if (post.get('post_number') % 3 === 0) { // after every 3 posts
return helper.rawHtml(`
<div class="lead_static_wrapper"><p>Label</p>
<div class="proper-ad-unit">
<div id="pr-ad-nr_main_1">
<script>propertag.cmd.push(function() { proper_display('nr_main_1'); });</script>
</div>
</div>
</div>
`);
}
});
</script>
Is there a way to edit the JS structure so this works?
I'm trying to make this work for Discourse forums. Any help is appreciated! Thanks!

Use a backslash to escape the closing slash.
<script>propertag.cmd.push(function() { proper_display('nr_main_1'); });<\/script>

Related

get a object value from a json API by Index in a forEach loop in JavaScript?

I am trying to learn how to use fetch() APIs this weekend...
and I saw this interesting API service, and I tried to learn how to use this
and I get a little problem, with javascript
the problem
I want to get the data from a .Json (and this works fine),
but when I want to put the values in the <div> and getting by object[index] is not showing anything
from what I know it seems possible,
but in this case, is not (...I search everywhere on the internet, no result)
basically...
this don't work object[index]; //index variable, is a number
this works object.object1; //normal method
what I tried
yes, I tried the traditional method using obj1.obj2 and is working fine, with the result I want!
but is not efficient, like I want.
because I want to get the values by index
and put the value in the <div>
with the index of the NodeListOf<element>
complete code, I wrote
open the snippet to see the code
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioText.forEach((item, index) => {
item.textContent = orario[index];
console.log(item.textContent + "" + index);
});
}
fetchPreghieraTime();
<div class="container">
<div class="tempo-preghiera-container">
<!-- 1 -->
<div class="tempo-fajr">
<div class="nome-preghiera">fajr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 2 -->
<div class="tempo-duhr">
<div class="nome-preghiera">duhr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 3 -->
<div class="tempo-asr">
<div class="nome-preghiera">asr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 4 -->
<div class="tempo-maghrib">
<div class="nome-preghiera">maghrib</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 5 -->
<div class="tempo-isha">
<div class="nome-preghiera">isha</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
</div>
</div>
<script src="./script.js"></script>
What do I mean by efficient?
this is the idea to write less, simpler code:
elementClass.forEach((item, index) => {
item.textContent = object[index];
});
you can see how inefficient method below, that is working
elementClass[0].textContent = object.Fajr;
elementClass[1].textContent = object.Dhuhr;
elementClass[2].textContent = object.Asr;
elementClass[3].textContent = object.Maghrib;
elementClass[4].textContent = object.Isha;
if you can I want the less code, or the simpler solution
( I don't want you to give a faster program possible, no no, for me if is simple logic that is enough for me )
(think if I need to write all the name of the object if there is like 50 items, etc..., that is why)
the first Idea is coming to my mind because of arrays...
and in arrays, you can use brackets with a number, that start with 0, and that is (is not working)
the problem
code doesn't work
let orarioText = document.querySelectorAll('.orario');
//there are 5 elements with the same class
orarioText.forEach((item, index) => {
item.textContent = orarioJson.data.timings[index];
});
this is WORKING fine
let orarioText = document.querySelectorAll('.orario');
//there are 5 elements with the same class
orarioText.forEach((item, index) => {
item.textContent = orarioJson.data.timings.Fajr; //here you see the [index] is replaced by the actual name
});
if you want to try also, here is the API I used
here is the API service link, I usedhttp://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8
and this is how it looks:
{"code":200,"status":"OK","data":{"timings":{"Fajr":"05:31","Sunrise":"07:19","Dhuhr":"12:37","Asr":"15:26","Sunset":"17:56","Maghrib":"17:56","Isha":"19:26","Imsak":"05:21","Midnight":"00:37"}
in case, is not clear the problem to you:
you can write a comment, asking for more info, I will answer it :)
short summary of what I asked
I want that this HTML
<!-- 0 -->
<div class="myClass"></div>
<!-- 1 -->
<div class="myClass"></div>
<!-- 2 -->
<div class="myClass"></div>
<!-- 3 -->
<div class="myClass"></div>
<!-- 4 -->
<div class="myClass"></div>
to become like this HTML after JS
<!-- 0 -->
<div class="myClass">obj1 value</div>
<!-- 1 -->
<div class="myClass">obj2 value</div>
<!-- 2 -->
<div class="myClass">obj3 value</div>
<!-- 3 -->
<div class="myClass">obj4 value</div>
<!-- 4 -->
<div class="myClass">obj5 value</div>
I hope there is someone amazing helpful developer,
who have more experience,
that can help me
(and help also the future developers who see this question)
and thank you all the community!
You can get the property name that you need from the parent element. It has it in its class name "tempo-....". It just needs one change in the HTML, as you used a different spelling for dhurh. So align that with the spelling in the JSON response.
Here is how you can extract that name from that "tempo" class and then use it to access the timing from the response object:
Find the parent element with .parentNode
Get the class attribute value with .className
Extract the part after "tempo-" using .match and the first entry in the returned array
Convert the first letter to a capital and the rest to lowercase.
Use it as a dynamic property
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioText.forEach((item, index) => {
let name = item.parentNode.className.match(/(?<=\btempo-)\w+/)[0];
item.textContent = orario[name[0].toUpperCase() + name.slice(1).toLowerCase()];
});
}
fetchPreghieraTime();
<div class="container">
<div class="tempo-preghiera-container">
<!-- 1 -->
<div class="tempo-fajr">
<div class="nome-preghiera">fajr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 2 -->
<div class="tempo-dhuhr">
<div class="nome-preghiera">duhr</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 3 -->
<div class="tempo-asr">
<div class="nome-preghiera">asr</div>
<div class="orario ">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 4 -->
<div class="tempo-maghrib">
<div class="nome-preghiera">maghrib</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
<!-- 5 -->
<div class="tempo-isha">
<div class="nome-preghiera">isha</div>
<div class="orario">error</div>
<!-- this error text, It will change dinamically with JS -->
</div>
</div>
</div>
<script src="./script.js"></script>
I will answer the same question, so I will help someone in the future :)
short answer
with .JSON format,
❌ you can't use the bracket with a number variable
orario[index]
✅ inside the brackets, you need to put a string (for example ["Fajr"], and is like writing .Fajr)
and so there isn't any method to access this by JSON!
but... I found a solution for you!
like you said also in the question, this method works very well in arrays
so we need to do something like this pseudocode:
FETCH -> JSON -> ARRAY -> ARRAY[index]
I saw on the internet that javascript, has this functionality, so you can use it too!
Object.values(orario);
more details about: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
so...
I put this in variable called orarioArray, so is simple for you!
const orarioArray = Object.values(orario);
now what you need is only add this to your forEach loop
orarioText.forEach((item, index) => {
item.textContent = orarioArray[index];
});
edited complete code:
let allTempoContainer = document.querySelector('.all-tempo-container');
let orarioArrayValue;
let orarioArrayName;
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
orarioArrayValue = Object.values(orario);
orarioArrayName = Object.keys(orario);
for (let index = 0; index < orarioArrayName.length; index++) {
createOrarioCard(index);
}
}
function createOrarioCard(index) {
var OrarioCardTemplate = document.querySelectorAll("template")[0];
var OrarioCardClone = OrarioCardTemplate.content.cloneNode(true);
allTempoContainer.appendChild(OrarioCardClone);
let orarioText = document.querySelectorAll('.orario');
let preghieraText = document.querySelectorAll('.nome-preghiera');
preghieraText[index].textContent = orarioArrayName[index];
orarioText[index].textContent = orarioArrayValue[index];
}
fetchPreghieraTime();
<div class="container">
<div class="all-tempo-container">
<!-- here it will generate the code -->
</div>
</div>
<template>
<div class="orario-container" style="display: flex; justify-content: space-between;">
<div class="nome-preghiera">loading...</div>
<div class="orario">loading...</div>
</div>
</template>
<script src="./script.js"></script>
previus code:
let orarioText = document.querySelectorAll('.orario');
const fetchPreghieraTime = async() => {
const data = await fetch('http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8');
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
// JSON to Array
const orarioArray = Object.values(orario);
orarioText.forEach((item, index) => {
item.textContent = orarioArray[index];
});
}
fetchPreghieraTime();
<!-- 0 -->
<div class="orario"></div>
<!-- 1 -->
<div class="orario"></div>
<!-- 2 -->
<div class="orario"></div>
<!-- 3 -->
<div class="orario"></div>
<!-- 4 -->
<div class="orario"></div>
try this
<div class="container">
<div class="tempo-preghiera-container">
</div>
</div>
const fetchPreghieraTime = async () => {
const data = await fetch(
"http://api.aladhan.com/v1/timingsByCity?city=Milano&country=Italy&method=8"
);
const orarioJson = await data.json();
const orario = orarioJson.data.timings;
let orarioText = document.querySelector(".tempo-preghiera-container");
for (const property in orario) {
if (property == "Sunset"
|| property == "Sunrise"
|| property == "Midnight" ) continue;
let div = document.createElement("div");
div.classList.add("orario");
let text = document.createTextNode(property + " - " + orario[property]);
div.appendChild(text);
orarioText.appendChild(div);
}
};
fetchPreghieraTime();
output
<div class="container">
div class="tempo-preghiera-container">
<div class="orario">Fajr - 05:30</div>
<div class="orario">Dhuhr - 12:37</div>
<div class="orario">Asr - 15:28</div>
<div class="orario">Maghrib - 17:57</div>
<div class="orario">Isha - 19:27</div>
<div class="orario">Imsak - 05:20</div>
<div class="orario">Midnight - 00:37</div>
</div>
</div>

Filter data in ng-repeat to display only the clicked item with Angularjs

Please help a little bit.
I have a list of 7 events displayed already with Angularjs. I'd like when I click on the <h2> (the event name) of some event, to open an ovelay that displays the same data from the database but only for this event which is clicked.
I'm sure that 'filter' will do the work but it seems I'm doing something wrong.
Here is my code. The ng-app and ng-controller are in the <main> tag.
Angularjs version: 1.7.9
My Html:
<main ng-app="eventsApp" ng-controller="eventsCtrl">
<!-- Overlay that holds and displays a single event -->
<div>
<div ng-repeat="x in singlePageEvent | filter:hasName(x.eventName)">
<div>
<img ng-src="{{x.eventImgSrc}}" alt="{{x.eventImgName}}"/>
<h2 class="event-name">{{x.eventName}}</h2>
<p>{{x.eventTime}}</p>
<p>{{x.eventPlace}}</p>
</div>
</div>
</div>
<!-- A list with all the events -->
<div ng-repeat="x in events">
<div>
<img ng-src="{{x.eventImgSrc}}" alt="{{x.eventImgName}}"/>
<h2 ng-click="singleEventOpen(x)" class="event-name">{{x.eventName}}</h2>
<p>{{x.eventTime}}</p>
<p>{{x.eventPlace}}</p>
</div>
</div>
</main>
My script:
let eventsApp = angular.module('eventsApp', []);
this filter below is not working at all. It continues to show all the events.
eventsApp.filter('hasName', function() {
return function(events, evName) {
var filtered = [];
angular.forEach(events, function(ev) {
if (ev.eventName && ev.eventName.indexOf(evName) >-1) {
filtered.push(ev);
}
});
return filtered;
}
});
eventsApp.controller('eventsCtrl', function($scope, $http) {
let x = window.matchMedia("(max-width: 450px)");
let singleEventOverlay = angular.element(document.querySelector('div.single-event.overlay'));
let singleEvent = singleEventOverlay;
function responsiveEventImages(x) { //this displays the list with events
if (x.matches) {
$http.get('./includes/events_res.inc.php').then(function(response) {
$scope.events = response.data.events_data;
});
} else {
$http.get('./includes/events.inc.php').then(function(response) {
$scope.events = response.data.events_data;
});
}
}
...and then by invoking singleEventOpen() the overlay appears, but it displays all the data, not just the clicked event
$scope.singleEventOpen = function(singleEvent) {
let clickedEvent = singleEvent.eventName; //I got the value of each h2 click thanx to #georgeawg but now what?
console.log("Fetching info for ", singleEvent.eventName);
$http.get('./includes/single_event.inc.php').then(function(response) {
$scope.singlePageEvent = response.data.events_data;
});
singleEventOverlay.removeClass('single-event-close').addClass('single-event-open');
}
});
The php file with the database extraction is working fine so I won't display it here.
What should I do to make the overlay display only the event which <h2> is clicked?
Here is a pic of the list with events
Here is a pic of the overlay
Thanx in advance.
EDITED
I got the value of each h2 click thanx to #georgeawg but now what?
UPDATE
Hey, thanx a lot #georgeawg . After many attempts I finally did this:
$scope.singleEventOpen = function(singleEvent) {
$http.get('./includes/single_event.inc.php').then(function(response) {
let allEvents = response.data.events_data;
for (var i = 0; i < allEvents.length; i++) {
singleEvent = allEvents[i];
}
});
console.log('Fetching data for', singleEvent);
$scope.ex = singleEvent;
});
And it works well.
Change the ng-click to pass an argument to the singleEventOpen function:
<div ng-repeat="x in events">
<div>
<img ng-src="{{x.eventImgSrc}}" alt="{{x.eventImgName}}"/>
<h2 ng-click="singleEventOpen(x)" class="event-name">{{x.eventName}}</h2>
<p>{{x.eventTime}}</p>
<p>{{x.eventPlace}}</p>
</div>
</div>
Then use that argument:
$scope.singleEventOpen = function(singleEvent) {
console.log("Fetching info for ", singleEvent.eventName);
//...
//Fetch and filter the data
$scope.ex = "single item data";
}
Adding an argument is the key to knowing which <h2> element was clicked.
Update
Don't use ng-repeat in the overlay, just display the single item:
<!-- Overlay that holds and displays a single event -->
̶<̶d̶i̶v̶ ̶n̶g̶-̶r̶e̶p̶e̶a̶t̶=̶"̶x̶ ̶i̶n̶ ̶s̶i̶n̶g̶l̶e̶P̶a̶g̶e̶E̶v̶e̶n̶t̶ ̶|̶ ̶f̶i̶l̶t̶e̶r̶:̶h̶a̶s̶N̶a̶m̶e̶(̶x̶.̶e̶v̶e̶n̶t̶N̶a̶m̶e̶)̶"̶>̶
<div ng-if="ex"">
<div>
<img ng-src="{{ex.eventImgSrc}}" alt="{{ex.eventImgName}}"/>
<h2 class="event-name">{{ex.eventName}}</h2>
<p>{{ex.eventTime}}</p>
<p>{{ex.eventPlace}}</p>
</div>
</div>

Append script to ID using short code?

I have code like :
<div id="content">
<div id="widget1"></div>
<div id="widget89"></div>
<div id="widget78"></div>
..............
<div id="widget(anyIndex)"></div>
</div>
By adding content into widget (HTML/JS widget) I have :
<div id="content"
<div id="widget1">
<script type='text/javascript'>
jQuery("#widget1").selectme({
Numpost:4,
Stylepost:"papa",
});
</script>
</div>
<div id="widget89">
<script type='text/javascript'>
jQuery("#widget89").selectme({
Numpost:7,
Stylepost:"popo",
});
</script>
</div>
..............
<div id="widget(anyIndex)">.....</div>
</div>
It is so manual and time-consuming.
Now, I want use short code instead of repeating too much Javascript in each div like :
<div id="content"
<div id="widget1">[4][papa]</div>
<div id="widget89">[7][popo]</div>
..............
<div id="widget(anyIndex)">...</div>
</div>
JS :
<script>
(function (a) {
a.selectme = function (c, b) {
var d = this;
d.init = function () {
d.options = a.extend({}, a.selectme.defaultOptions, b);
...................something
};
d.init()
};
a.selectme.defaultOptions = {
Numpost:4,
Stylepost:"Enter your style",
};
a.fn.selectme = function (b) {
return this.each(function () {
(new a.selectme(this, b))
})
}
})(jQuery);
</script>
Notice :Widget(anyindex) is catch automatically. For example: widget89 is set current but I don't know the index of that widget (index = 89), just sure that I am inputting Javascript/Jquery code into it. When I add new widget I will have new index, for example : widget105 or also widget200 (anyindex)
How can I do that. Thanks for your help.
Here's a way using data attributes in markup and a simple each loop to initialize. Add data- attributes for the variables you need to specify in plugin.
<div id="widget89" data-numpost="7" data-style="popo">
alert( $('#widget89').data('numpost') );
To get index of widgets create a collection of them first to use to index against:
Using $.each to intialize the whole collection will give you the index of widget in collection ( I'm not clear what you need it for):
$('[id^=widget]').each(function(idx){
var $this=$(this), data=$this.data, INDEX=idx;
$this.selectme({
Numpost:data.numpost,
Stylepost:data.style
})
})
you can use a function
function setwidget(id,post,style)
{
jQuery("#"+id).selectme({
Numpost:post,
Stylepost:style
});
}
now call like
setwidget("widget1",4,"papa");
setwidget("widget89",7,"popo");

DOM reading in jquery

I'm trying to do a filter that will show or hide <div> regarding the data-type they have in their tags.
Here is my Javascript :
var course_difficulty_level_filter= function(el,level)
{
this.el = el;
this.el.closest('#courses_content').find("div").hide();
if(level != "00"){
this.el.closest('#courses_content').find('div[data-difficulty="'+level+'"]').show();
console.log("show difficulty_level : "+ level);
} else {
this.el.closest('#courses_content').find("div").show();
console.log("show difficulty_level : all");
};
}
$('#course_filter_level1').click(function(){
$(this).click(course_difficulty_level_filter($(this),"1"));
});
And here is my HTML :
<div id="coursefilter">
<div id="coursefilter_content" class="hide">
<div id="coursefilter_content_text">
<div id="course_filter_level_text"><p class="course_filter">Level: </p></div>
</div>
<div id="coursefilter_content_icons">
<div id="course_filter_level">
<div id="course_filter_level1" class="opacityquarter">
<div id="level1_rectangle1"></div>
<div id="level1_rectangle2"></div>
<div id="level1_rectangle3"></div>
<div id="level1_rectangle4"></div>
</div>
</div>
</div>
</div>
</div>
<!--Courses - Course Overviews-->
<div id="courses">
<div id="courses_content" class="hide">
<div class="course_overview_content_even" data-difficulty="1" data-lang="en"></div>
</div>
</div>
I successfully get the console.log => show difficulty_level : 1, so my script is "working", but I think it can't navigate trough the DOM, but I don't find why.
Are you simply looking for:
$('div[data-difficulty="'+level+'"]').show();
$('div[data-difficulty="'+level+'"]').hide();
jQuery has rich support for querying HTML attibutes: http://api.jquery.com/category/selectors/attribute-selectors/
I think this code is the problem:
this.el.closest('#courses_content')
The closest function works back up the parents to find the selector, but #courses_content is not a parent of #course_filter_level1 (the value passed in as el).
Try changing those references to just be:
$('#courses_content')
There should be no need to find this element relative to the passed in element as I hope there is only one div with the id courses_content as ID's are supposed to be unique within the document.
The whole function can be changed to this:
// removed el, so it must be removed from the calling function
var course_difficulty_level_filter= function(level)
{
var coursesContent = $('#courses_content');
coursesContent.find("div").hide();
if(level != "00"){
coursesContent.find('div[data-difficulty="'+level+'"]').show();
console.log("show difficulty_level : "+ level);
} else {
coursesContent.find("div").show();
console.log("show difficulty_level : all");
};
}

Javascript Elements with class / variable ID

There's a page with some HTML as follows:
<dd id="fc-gtag-VARIABLENAMEONE" class="fc-content-panel fc-friend">
Then further down the page, the code will repeat with, for example:
<dd id="fc-gtag-VARIABLENAMETWO" class="fc-content-panel fc-friend">
How do I access these elements using an external script?
I can't seem to use document.getElementByID correctly in this instance. Basically, I want to search the whole page using oIE (InternetExplorer.Application Object) created with VBScript and pull through every line (specifically VARIABLENAME(one/two/etc)) that looks like the above two into an array.
I've researched the Javascript and through trial and error haven't gotten anywhere with this specific page, mainly because there's no tag name, and the tag ID always changes at the end. Can someone help? :)
EDIT: I've attempted to use the Javascript provided as an answer to get results, however nothing seems to happen when applied to my page. I think the tag is ALSO in a tag so it's getting complicated - here's a major part of the code from the webpage I will be scanning.
<dd id="fc-gtag-INDIAN701" class="fc-content-panel fc-friend">
<div class="fc-pic">
<img src="http://image.xboxlive.com/global/t.58570942/tile/0/20400" alt="INDIAN701"/>
</div>
<div class="fc-stats">
<div class="fc-gtag">
<a class="fc-gtag-link" href='/en-US/MyXbox/Profile?gamertag=INDIAN701'>INDIAN701</a>
<div class="fc-gscore-icon">3690</div>
</div>
<div class="fc-presence-text">Last seen 9 hours ago playing Halo 3</div>
</div>
<div class="fc-actions">
<div class="fc-icon-actions">
<div class="fc-block">
<span class="fc-buttonlabel">Block User</span>
</div>
</div>
<div class="fc-text-actions">
<div class="fc-action"> </div>
<span class="fc-action">
View Profile
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Compare Games
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Message
</span>
<span class="separator-icon">|</span>
<span class="fc-action">
Send Friend Request
</span>
</div>
</div>
</dd>
This then REPEATS, with a different username (the above username is INDIAN701).
I tried the following but clicking the button doesn't yield any results:
<script language="vbscript">
Sub window_onLoad
Set oIE = CreateObject("InternetExplorer.Application")
oIE.visible = True
oIE.navigate "http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=12"
End Sub
</script>
<script type="text/javascript">
var getem = function () {
var nodes = oIE.document.getElementsByTagName('dd'),
a = [];
for (i in nodes) {
(nodes[i].id) && (nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
}
</script>
<body>
<input type="BUTTON" value="Try" onClick="getem()">
</body>
Basically I'm trying to get a list of usernames from the recent players list (I was hoping I wouldn't have to explain this though :) ).
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
alert(a[0]);
};
please try it by clicking here!
var getem = function () {
var nodes = document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i]));
}
alert(a[0].id);
alert(a[1].id);
};
try it out on jsbin
<body>
<script type="text/javascript">
window.onload = function () {
var outputSpan = document.getElementById('outputSpan'),
iFrame = frames['subjectIFrame'];
iFrame.document.location.href = 'http://live.xbox.com/en-US/friendcenter/RecentPlayers?Length=1';
(function () {
var nodes = iFrame.document.getElementsByTagName('dd'),
a = [];
for (var i in nodes) if (nodes[i].id) {
(nodes[i].id.match(/fc\-gtag\-/)) && (a.push(nodes[i].id.split('-')[2]));
}
for (var j in a) if (a.hasOwnProperty(j)) {
outputSpan.innerHTML += (a[j] + '<br />');
}
})();
};
</script>
<span id="outputSpan"></span>
<iframe id="subjectIFrame" frameborder="0" height="100" width="100" />
</body>
What does "I can't seem to use document.getElementsByID correctly in this instance" mean? Are you referring to the fact that you are misspelling getElementByID?
So...something like this (jQuery)?
var els = [];
$('.fc-content-panel.fc-friend').each(function() {
els.push(this));
});
Now you have an array of all the elements that have both of those classes.

Categories