jQuery to iterate through class elements, grab text, insert elsewhere - javascript

I need to programmatically extract titles within a webpage, inject anchor links right above those titles and then inject navigation links near the top of the page that will link to those anchors within the same page.
I need jQuery to select all headings with the class of 'iphorm-group-title’ and extract the text.
Above each heading, excluding the first heading, an anchor tag needs to be injected so that a visitor can link to that section of the page.
The text of each heading, excluding the first heading, needs to be injected before the first heading and linked to all the anchor tags that were injected in the previous step.
This form is generated by a plugin or I would just edit the HTML.
For reference, the page is located at:
http://mountpleasantmagazine.com/BestOfBallot/
Here is an example of the HTML as of now.
<div>
<div>
<div class="iphorm-group-title">VOTER INFO</div>
</div>
<div>
<div class="iphorm-group-title">SHOPPING & GOODS</div>
</div>
<div>
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
<div>
<div class="iphorm-group-title">ENTERTAINMENT & LEISURE</div>
</div>
</div>
Here is some JS that will grab the elements and loop through the text, which is the point where I'm stuck.
jQuery('.iphorm-group-title').each(function () {
console.log(jQuery(this).text());
});
Here is how the HTML is expected to look after injecting the code.
<div>
<div>
SHOPPING & GOODS | FOOD & DRINK | <a href="#entertainmentleisure">ENTERTAINMENT & LEISURE</ a>
</div>
<div>
<div class="iphorm-group-title">VOTER INFO</div>
</div>
<div>
<a name="shoppinggoods"></a>
<div class="iphorm-group-title">SHOPPING & GOODS</div>
</div>
<div>
<a name="fooddrink"></a>
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
<div>
<a name="entertainmentleisure"></a>
<div class="iphorm-group-title">ENTERTAINMENT & LEISURE</div>
</div>
</div>

I just made a code snippet for you hope so it's the exact what you needed.
var listElement=jQuery("<div id='menuList'></div>").insertBefore(".iphorm-elements");
jQuery(".iphorm-elements .iphorm-group-wrap:not(:first-child)")
.each(function() {
if (jQuery(this)
.not(".iphorm-group-wrap:first")) {
var heading = jQuery(this)
.find(".iphorm-group-title");
var headingName = heading.text()
.split(' ')
.join('')
.replace('&', '');
var lowerHeading = headingName.toLowerCase();
var anchorUrl = [lowerHeading.slice(0, 0), lowerHeading.slice(0)].join('');
var anchorText = heading.text();
var anchorLink=jQuery('<a name="' + anchorUrl + '"></a>')
.insertBefore(heading);
var anchorLink2=jQuery('' + anchorText + '' +"<span> | </span>")
.insertBefore(heading);
jQuery(listElement).append(anchorLink2);
}
});
jQuery("#menuList span:last-child").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="iphorm-elements">
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">VOTER INFO</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">SHOPPING & GOODS</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">FOOD & DRINK</div>
</div>
</div>
<div class="iphorm-group-wrap">
<div class="iphorm-group-title-description-wrap">
<div class="iphorm-group-title">ENTERTAINMENT & LEISURE</div>
</div>
</div>
</div>

Related

Link simillary name classes so that when one is clicked the other is given a class

Basically, I'm asking for a way to optimize this code. I'd like to cut it down to a few lines because it does the same thing for every click bind.
$("#arch-of-triumph-button").click(function(){
$("#arch-of-triumph-info").addClass("active-info")
});
$("#romanian-athenaeum-button").click(function(){
$("#romanian-athenaeum-info").addClass("active-info")
});
$("#palace-of-parliament-button").click(function(){
$("#palace-of-parliament-info").addClass("active-info")
});
Is there a way to maybe store "arch-of-triumph", "romanian-athenaeum", "palace-of-parliament" into an array and pull them out into a click bind? I'm thinking some concatenation maybe?
$("+landmarkName+-button").click(function(){
$("+landmarkName+-info").addClass("active-info")
});
Is something like this even possible?
Thanks in advance for all your answers.
EDIT: Here's the full HTML.
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button"></div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button"></div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Assuming you're not able to modify your HTML markup (in which case with use of CSS classes would be cleaner), a solution to your question would be as shown below:
// Assign same click handler to all buttons
$("#arch-of-triumph-button, #romanian-athenaeum-button, #palace-of-parliament-button")
.click(function() {
// Extract id of clicked button
const id = $(this).attr("id");
// Obtain corresponding info selector from clicked button id by replacing
// last occurrence of "button" pattern with info.
const infoSelector = "#" + id.replace(/button$/gi, "info");
// Add active-info class to selected info element
$(infoSelector).addClass("active-info");
});
Because each .landmark-button looks to be in the same order as its related .landmark-info, you can put both collections into an array, and then when one is clicked, just find the element with the same index in the other array:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
This does not rely on IDs at all - feel free to completely remove those from your HTML to declutter, because they don't serve any purpose now that they aren't being used as selectors.
Live snippet:
const buttons = [...$('.landmark-button')];
const infos = [...$('.landmark-info')];
$(".landmark-button").click(function() {
const i = buttons.indexOf(this);
$(infos[i]).addClass('active-info');
});
.active-info {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Arch of Triumph</span>
</div>
<div class="landmark-button" id="arch-of-triumph-button">click</div>
</div>
</div>
<div class="landmark-wrapper">
<div class="page-content landmark">
<div class="heading span-after">
<span>Romanian Athenaeum</span>
</div>
<div class="landmark-button" id="romanian-athenaeum-button">click</div>
</div>
</div>
----------------------------------------------------------
<div class="landmarks-info-wrapper">
<div class="landmark-info" id="arch-of-triumph-info">
<div class="info-landmark section">
<span class="landmark-title">Arch of Triumph</span>
<span class="landmark-coord">44°28′1.99″N 26°4′41.06″E</span>
</div>
</div>
<div class="landmark-info" id="romanian-athenaeum-info">
<div class="info-landmark section">
<span class="landmark-title">The Romanian Athenaeum</span>
<span class="landmark-coord">44.4413°N 26.0973°E</span>
</div>
</div>
Older answer, without knowing the HTML: You can extract the ID of the clicked button, slice off the button part of it, and then select it concatenated with -info:
$(".landmark-button").click(function() {
const infoSel = this.id.slice(0, this.id.length - 6) + 'info';
$(infoSel).addClass('active-info');
});
A much more elegant solution would probably be possible given the HTML, though.

Background url from href

I am trying to get url from href and paste it in background image.
The problem is that it is applying to just first div not on all div. Is this possible without giving unique classes?
HTML
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
<div id="main-bg"> text
<div id="inner-content"> </div>
</div>
JS
$('#main-bg').css(
'background-image', 'url(' + $('#inner-content a').attr('href') + ')'
);
JSFIDDLE: https://jsfiddle.net/pr07zymf/
An id MUST be unique to each element! Using it multiple times may work at times in CSS, though, JavaScript isn't so forgiving. The reason only the first <div> is styled is because JavaScript ignores all other elements with the same id.
You can use classes instead as shown in the example below!
Example Code:
/* Iterate over every element having the given class. */
$('.main-bg').each(function (index, element) {
/* Cache a jQuery instance of the element. */
var el = $(element);
/* Get the 'href' and assign it as the 'background-image' for each element. */
el.css('background-image', 'url(' + el.find('.inner-content a').attr('href') + ')');
});
.main-bg {color: #fff}
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
<div class="main-bg"> text
<div class="inner-content">
</div>
</div>
When you are using HTML, please remember, the ID should always be UNIQUE.
You cannot make them the same name like "main-bg".
Solutions:
1, change their id's name to <div id ="main-bg1">, <div id ="main-bg2">, <div id ="main-bg3">, and <div id ="main-bg4">
2, use CLASS like
<div class="main-bg"> text
<div class="inner-content"> </div>
And remember, every time when you do
$('#ID')
or
document.getElementById(ID)
It will always choose the FIRST element which has this ID.

How to find the html after unwrap the div element using Jquery

I have following html code
<div class="main">
<div id="magicdomid2" class="">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
</div>
<div id="magicdomid3" class=""><br></div>
<div id="magicdomid4" class="">
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
</div>
<div id="magicdomid5" class=""><br></div>
<div id="magicdomid6" class="">
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
</div>
Here is the html content
var html = $(".main").html();
I need to get the following htm in a variable
<div class="main">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
<br>
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
<br>
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
I tried following code
var text = $('div.main div').contents().unwrap().siblings('div').remove();
The variable "text" will get an object and i need the html content in a variable.. Please help me to find it.
Is their any possibility to export the customised html or xml format from etherpad ??
May it Help!
var htm = "";
$("div[id^='magicdomid']").each(function(i,val){
htm = htm + $(this).html();
});
$("div[class='main']").empty().html(htm);
//You can also use this for the same
$("div[id^='magicdomid']")
.contents()
.filter(function() {
return this.nodeType === 1;
})
.unwrap()
.end()
.filter(function() {
return this.nodeType === 3;
})
.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div id="magicdomid2" class="">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
</div>
<div id="magicdomid3" class=""><br></div>
<div id="magicdomid4" class="">
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
</div>
<div id="magicdomid5" class=""><br></div>
<div id="magicdomid6" class="">
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
</div>
unwrap and contents might not be the best to use in this case as they tend to modify the actual DOM tree rather than the html variable.
Try this:
// create empty div
var htmlContent = $('<div class="main"></div>');
// loop over magic class & append its content
$('.main .magic').each(function(i, n) {
htmlContent.append($(this).html());
});
// wrap & move one level above to get "main" div in html string
htmlString = htmlContent.wrap('<div></div>').parent().html();
console.log(htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div id="magicdomid2" class="magic">
<center style="width:100%;margin:0 auto;list-style-position:inside;display:block;text-align:center">
<h1><span class="b"><b>Welcome to Etherpad!</b></span></h1>
</center>
</div>
<div id="magicdomid3" class="magic"><br></div>
<div id="magicdomid4" class="magic">
<span class="">This pad text is synchronized as you type, so that everyone viewing this page sees the same text. This allows you to collaborate seamlessly on documents!
</span>
</div>
<div id="magicdomid5" class="magic"><br></div>
<div id="magicdomid6" class="magic">
<span class="">Get involved with Etherpad at </span>
<span class=" url">http://etherpad.org
</span>
</div>
</div>

Open div panel inbetween two tweets?

I'm working on a UI that has Twitter feeds. I want to be able to open a panel in the middle of two tweets, pushing the tweet below downwards. This functionality can be seen in tweet clients like TweetBot. As each new tweet in the stream popped up it would push each one below it down as well. Tool bar would be the same for all tweets.
Here is what I have for the JS:
$(document).ready(function() {
hidden = true;
$("div#tweetcontainer").click(function() {
if (hidden == false) {
$("div#toolbar").slideUp('fast');
hidden = true;
} else {
$("div#toolbar").slideDown('fast');
hidden = false;
}
});
});​
Here is the markup of the HTML:
<div id="wrapper">
<!------------- Indivdual Tweet -------------------------->
<div id="tweetcontainer">
<div id="avatarcontainer">
<div id="avatar"></div>
</div>
<div id="content">
<div id="tweetheader">
<div id="name">
<h1>John Drake</h1>
</div>
<div id="tweethandle">
<h2>#Drakejon</h2>
</div>
<div id="tweettime">10m</div>
</div>
<div>
<p>Exceptional Buys Ranger To Give Monitoring Shot In The Arm To Its 'DevOps' Platform http://tcrn.ch/11m3BrO by #sohear </p>
</div>
</div>
</div>
<!------------- Indivdual Tweet 2 -------------------------->
<div id="tweetcontainer">
<div id="avatarcontainer">
<div id="avatar"></div>
</div>
<div id="content">
<div id="tweetheader">
<div id="name">
<h1>John Drake</h1>
</div>
<div id="tweethandle">
<h2>#Drakejon</h2>
</div>
<div id="tweettime">10m</div>
</div>
<div>
<p>Exceptional Buys Ranger To Give Monitoring Shot In The Arm To Its 'DevOps' Platform http://tcrn.ch/11m3BrO by #sohear </p>
</div>
</div>
</div>
<!-------------Tool Bar -------------------------------->
<div id="toolbar">
<div class="toolset">reply</div>
<div class="toolset">Retweet</div>
<div class="toolset">Favorite</div>
<div class="toolset">Track</div>
<div class="toolset">Details</div>
</div>
</div>
Do
$toolbar = $(.toolbar).clone();
$(this).after($toolbar);
I guess you will have to do something like
$(.toolbar).addClass("hidden");
before you appending it to the div, and then do
if ($(.toolbar)).hasClass("hidden"){
...pulldown...
}
or something to keep it disappeared and make it pullDown after appending.

Generate link based on data attributes

I am trying to write a little jQuery script that checks a set of div's to see if they have a data-name attribute. For the ones that have a data-name, it will create a link. The href of that link should be the name of the data-value plus contain the file extension (eg. .txt).
Everything seems to work OK except when I try to add the data value onto the link. The ultimate result of this script is to output something like this for each of those div's:
<p class="data-link">Edit
Below is my script. I have identified that area that I am having issue with.
var dataNameWrappers = $("div#desktopSidebar div[data-name]");
dataNameWrappers.each(function() {
var dataNameWrappers_action = "" + $(this).attr("data-name");
$(this).prepend("<p class='edit-link'><a>Edit</a></p>");
var dataNameWrapperEditLink = $("div#desktopSidebar p.edit-link a");
dataNameWrapperEditLink.each(function() {
$(this).attr('href', <<stuck_here>>);
});
});
Any help will be great.
Thanks
As requested, here is my sidebar HTMl structure
<div id="desktopSidebar">
<div class="sidebar userbox">
<h3 class="sidebarheader"> Welcome {{username}}}</h3>
</div>
<div data-name="social_media_sitewide" class="sidebar socialmedia">
<h3 class="sidebarheader">Follow Tennis-Chat</h3>
</div>
<div data-name="site_promotions" class="sidebar promotions">
<h3 class="sidebarheader">Current Promotions</h3>
</div>
<div data-name="livescores" class="sidebar Livescores">
<h3 class="sidebarheader">Live Scores</h3>
</div>
<div class="sidebar tournaments">
<h3 class="sidebarheader">Tournaments</h3>
</div>
<div data-name="featured-profiles" class="sidebar profiles">
<h3 class="sidebarheader">Today's Profile: {{featured_profile_name}}</h3>
</div>
<div data-name="side_advertisment" class="sidebar Advertisement">
<h3 class="sidebarheader">Advertisement</h3>
</div>
<div class="sidebar Headlines">
<h3 class="sidebarheader">Tennis-Chat Headlines</h3>
</div>
<div class="sidebar mostrecent" id="mostRecentTopics">
<h3 class="sidebarheader">Most Recent Posts</h3>
</div>
</div>
I don't know why you are using a second loop to add the HREFs when you already have everything you need.
Working fiddle here: http://jsfiddle.net/Q4j8S/.
HTML:
<div id="desktopSidebar">
<div class="sidebar userbox">
<h3 class="sidebarheader"> Welcome {{username}}}</h3>
</div>
<div data-name="social_media_sitewide" class="sidebar socialmedia">
<h3 class="sidebarheader">Follow Tennis-Chat</h3>
</div>
<div data-name="site_promotions" class="sidebar promotions">
<h3 class="sidebarheader">Current Promotions</h3>
</div>
<div data-name="livescores" class="sidebar Livescores">
<h3 class="sidebarheader">Live Scores</h3>
</div>
<div class="sidebar tournaments">
<h3 class="sidebarheader">Tournaments</h3>
</div>
<div data-name="featured-profiles" class="sidebar profiles">
<h3 class="sidebarheader">Today's Profile: {{featured_profile_name}}</h3>
</div>
<div data-name="side_advertisment" class="sidebar Advertisement">
<h3 class="sidebarheader">Advertisement</h3>
</div>
<div class="sidebar Headlines">
<h3 class="sidebarheader">Tennis-Chat Headlines</h3>
</div>
<div class="sidebar mostrecent" id="mostRecentTopics">
<h3 class="sidebarheader">Most Recent Posts</h3>
</div>
</div>
JavaScript:
var dataNameWrappers = $("div#desktopSidebar div[data-name]");
dataNameWrappers.each(function() {
var dataNameWrappers_action = $(this).attr("data-name");
console.log('data-name ' + dataNameWrappers_action);
$(this).prepend('<p class="edit-link">Edit</p>');
/* Don't need this
var dataNameWrapperEditLink = $("div#desktopSidebar p.edit-link a");
dataNameWrapperEditLink.each(function() {
$(this).attr('href', dataNameWrappers_action);
});
*/
});
Instead of iterating through the a tags after you do the prepend, it may be better to make the HTML fragment with the desired href attribute.
Here is the code that accomplishes that:
$('#desktopSidebar .sidebar[data-name]').each(function(index, el){
var href = $(el).attr('data-name') + ".txt";
$(el).prepend('<p class="edit-link">Edit');
});

Categories

Resources