How to use ClassName add entries to a DIV - javascript

HTML source:
<span class="specLink">
<specialty><a title="Plastic Surgery" href="link2.aspx">Plastic Surgery</a></specialty>
</span>
<br />
<span class="specLink">
<specialty2><a title="Hand Surgery" href="link3.aspx">Hand Surgery</a></specialty2>
</span>
How can I create a JQuery script which runs during page load to displays the same list taking from the HTML Source listed above?
E.g.:
<div class="justPad">
<a title="Plastic Surgery" href="link2.aspx" class="defaultLinks">Plastic Surgery</a>
</div>
<div class="justPad">
<a title="Hand Surgery" href="link3.aspx" class="defaultLinks">Hand Surgery</a>
</div>
How I would like it to be:
var k = "";
$(".specLink").each(function() {
var aLink = $(".specLink").replace(<%-- Remove the <specialty#></specialty#> tags and only keep the anchor link --%>);
k += '<div class="justPad">'; //.. as many entries that shows up
k += aLink; //.. as many entries that shows up
k += '</div>'; //.. as many entries that shows up
});
//Once I have added
$(".addSpecialties").html(k);
Blank HTML:
<div class="serviceHolder brClear addSpecialties">
//add inside here from the JQuery above
</div>

Something like:
var specialties = $(".specLink a").map(function() {
return $('<div class="justPad">').append( $(this).clone() )[0];
}).toArray();
$(".addSpecialties").empty().append(specialties);

Related

How to pick out span tag that doesn't have a class

Using document.getElementsByClassName("span3 pickItem").outerHTML) I set a variable htmlData to contain:
<div itemscope="" class="span3 pickItem">
<p itemprop="name" class="name">
<a href="/user/view?id=4943">
<span>John Doe</span>
<br />
<span>'Arizona'</span>
<br />
<span>'Student'</span>
</a>
</p>
</div>
How can I pick each value from the span tag and console.log them as such:
console.log(...span[0]) output: John Doe
console.log(...span[1]) output: Arizona
console.log(...span[2]) output: Student
Could do something like this
let namesArr = [];
let name = document.querySelectorAll("span");
name.forEach(function(names) {
namesArr.push(names.innerHTML);//Stores all names in array so you can access later
});
console.log(namesArr[0]);
console.log(namesArr[1]);
console.log(namesArr[2]);
Something like this should work:
// console log all names
const items = document.querySelectorAll('div.pickItem span')
items.forEach(item => {
console.log(item.innerText)
})
// console each from array index
console.log(items[0].innerText)
console.log(items[1].innerText)
console.log(items[2].innerText)
let spans = document.getElementsByTagName('span');
console.log(spans[0].innerHTML); //'Joe Doe'
You don't even need the htmlData variable because the DOM elements already exist. If you want to learn about parsing a string of HTML (this is what your htmlData variable has in it) into DOM elements, you can reivew DOMParser.parseFromString() - Web APIs | MDN.
Select the anchor
Select its child spans and map their textContent properties
function getTextFromSpan (span) {
// Just return the text as-is:
// return span.textContent?.trim() ?? '';
// Or, you can also remove the single quotes from the text value if they exist:
const text = span.textContent?.trim() ?? '';
const singleQuote = `'`;
const hasQuotes = text.startsWith(singleQuote) && text.endsWith(singleQuote);
return hasQuotes ? text.slice(1, -1) : text;
}
const anchor = document.querySelector('div.span3.pickItem > p.name > a');
const spanTexts = [...anchor.querySelectorAll(':scope > span')].map(getTextFromSpan);
for (const text of spanTexts) {
console.log(text);
}
<div itemscope="" class="span3 pickItem">
<p itemprop="name" class="name">
<a href="/user/view?id=4943">
<span>John Doe</span>
<br />
<span>'Arizona'</span>
<br />
<span>'Student'</span>
</a>
</p>
</div>

Change text in div class with text from another

I'm trying to change the text in the div class "instock" with the words 'Made by' plus the "companyName" text
<div class="productDetails">
<div class="description">
<span class="companyName>The Company Name</span>
</div>
<div class="instock">Handmade to order</div>
<div>
I want instock to look like this:
<div class="instock">Made by The Company Name</div>
I've tried this
var companyName = document.getElementsByClassName('companyName');
var companyNameText = companyName.nodeValue;
var instock = document.getElementsByClassName('instock');
var instockAlt = instock.nodeValue;
instockAlt.textContent = 'Made by' + companyNameText;
Also as this might not always need to be done (when there is no company name for changing) I think I need to check if the span class is there first.
With JQuery, you can do the following
var companyName = $('.companyName').text();
if(companyName){
$('.instock').html('Made by ' + companyName);
}
With jQuery you could do:
$('.instock').html(function() {
if ( $(this).prev('.description').find('span').length ) return 'Made by ' + $(this).prev('.description').find('span').html()
})
jsFiddle example
You have a " missing in the <span>. The line:
var companyName = document.getElementsByClassName('companyName');
Returns a HTMLCollection. Either change it to:
var companyName = document.getElementsByClassName('companyName')[0];
var companyName = document.querySelector('.companyName');
If you are using jQuery, please use:
var companyName = $('.companyName');
var companyNameText = companyName.text();
var instock = $('.instock');
var instockAlt = instock.text();
instockAlt.text('Made by' + companyNameText);
The reason is, textContent is not available everywhere, while some browsers use innerText. jQuery takes care of browser incompatibilities like this.
Also, the final code is </div> not <div>.
If the whole code is a section block, then you need to use a contextual way:
$(function () {
$('.instock').each(function() {
if ( $(this).prev('.description').find('span').length )
$(this).text('Made by ' + $(this).prev('.description').find('span').text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="productDetails">
<div class="description">
<span class="companyName">The Company Name</span>
</div>
<div class="instock">Handmade to order</div>
</div>

How to extract Javascript array information and insert into DOM elements

Initially, I have the following:
<ul id="my_List">
...
</ul>
Using Javascript, I want to generate "li" elements within that ul block that use values for the text information from the array.
For example, I have a template:
<li>
<div>
<a href="#">
<span class="icon"></span>
<span class="text">[PLACEHOLDER HERE]</span>
<span class="icon"></span>
<span class="icon large"></span>
<br/>
<span class="information">[PLACEHOLDER HERE]</span>
<hr />
</a>
</div>
</li>
and I'm trying to figure out how to parse the information from my Javascript array into the [PLACEHOLDER HERE] blocks while still applying the whole template (all the internal tags and classes) in some kind of for loop. Is there a quick way of doing this or will I have to do a series of appends and whatnot to achieve my goal here?
array mapping is another option
var arr = [
{ a: 'foo', b: 'bar' },
{ a: 'foo 2', b: 'bar 2' },
];
var html = arr.map(function(item) {
return '<li>' +
'<span>' + item.a + '<span>' +
'<span>' + item.a + '<span>' +
'</li>';
}).join('');
document.getElementById('#list').innerHTML = html;
<ul id="#list"></ul>
Tried to create a model. Continue like this and create a model like you want.
<script language="JavaScript">
window.onload = function() {
function createTable(tableData) {
var ul = document.getElementById('my_List');
var li = document.createElement('li');
var div = document.createElement('div');
var ahref = document.createElement('a');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('span');
cell.innerHTML = cellData;
row.appendChild(cell);
});
ahref.appendChild(row);
});
div.appendChild(ahref);
li.appendChild(div);
ul.appendChild(li);
}
createTable([["row 1, cell 1", "row 1, cell 2"], ["row 2, cell 1", "row 2, cell 2"]]);
}
</script>
So you have an HTML element you want to use as a template -- simply clone it and populate as needed.
$("#create-more").on("click", function() {
// First, save references...
var myContentPane = $(".content-pane");
var myText = $(".form-text").val();
var myInfo = $(".form-info").val();
// This is a clone of our hidden template
var myTemplate = $("#template").clone();
// Replace placeholders in the template...
myTemplate.attr("id", "");
myTemplate.find(".text").text(myText);
myTemplate.find(".information").text(myInfo);
// Now we use the template!
myContentPane.append(myTemplate);
});
#template {
display: none;
}
label {
font-weight: bold;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="text-stuff">Some text:</label>
<input type="text" class="form-text" />
<label for="information">Some Info:</label>
<input type="text" class="form-info" />
<button id="create-more">
Create more
</button>
</form>
<div id="template">
<a href="#"><span class="icon" </span>
<span class="text">[PLACEHOLDER HERE]</span>
<span class="icon"></span>
<span class="icon large"></span>
<br/>
<span class="information">[PLACEHOLDER HERE]</span>
<hr />
</a>
</div>
<section class="content-pane">
</section>
A solution to this problem from scratch can get very messy; I'd recommend you make use of available libraries.
lodash has a great solution called _.template. Check out the docs here.
// constructing string like this for readability
var li = [
'<li>',
'<div><%=id%></div>',
'<div><%=name%></div>',
'</li>'
].join('');
var liTemplate = _.template(li);
var liOne = liTemplate({ id: '1', name: 'Hello' }); // => "<li><div>1</div><div>Hello</div></li>"
var liTwo = liTemplate({ id: '2', name: 'World' }); // => "<li><div>2</div><div>World</div></li>"
EDIT: In order to get those strings into your DOM, you could do the following:
var ul = document.getElementById('my_list');
ul.innerHTML = liOne + liTwo;

Getting row data in dynamically created listview

Hi i'm creating list view dynamically. I want to get the data of particular row on click, to proceed to further steps.
my code is as below
function getList(tx, results){
$('#DeliveryList').empty();
var len = results.rows.length;
for(var i=0; i <len; i++)
{
var deliveryItems = results.rows.item(i);
var html = '<li data-role="list-divider">'+deliveryItems.DeliveryName+ ' | ' + deliveryItems.PrimaryName+' <span class="ui-li-count">Copay ='+deliveryItems.Total+'</span> </li><li><a><img src="Pending"/><h3>'+deliveryItems.Name1+'</h3><p>'+deliveryItems.Address+'</p><p>'+deliveryItems.City+' <b></b></p><p><strong>'+deliveryItems.ContactNumber+'</strong></p><a href="#PrescriptionPage" class="cls_btn" id="btn_list" onclick = "Prescription()" >Delivary Details</a></a></li>';
$('#DeliveryList').append(html).trigger('create');
}
$('ul').listview('refresh');
}
My html file looks like
<div data-role="page" id="page3" >
<div data-role="header">
Back
<h1>Heading</h1>
Home
</div><!-- /header -->
<ul data-role="listview" id="DeliveryList" data-inset="true" data-theme="d" data-divider-theme="b"> </ul>
</div>
can any one help me to achieve the result. Thanks in Advance.
It worked for me with below code
$('ul').children('li').on('click', function () {
alert('Selected Name=' + $(this).text());
});
You're using jQuery already, why not use it to create these elements aswell? I asume getList() is bound to an event.
// Create the element
var li = $('<li></li>');
// Add your class
li.addClass('list-divider');
// Change the innerHTML
li.html('Your content');
// Then append it to the list
$('#DeliveryList').append(li);
Simply alter this code to your need. This example just adds one <li> element with a class and some content.
Good luck.

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