Finding the value of all H2s on a page with Javascript - javascript

I have been trying to find a solution on Google so I thought I would post it to the community. I need to use JavaScript to locate all the H2s on a page, get the innerHTML values and then loop them horizontally in a div (easy enough) to show a subheading anchor list at the top of the page. Can someone tell me or give me a hint on how I can use a JavaScript routine to locate all the H2s on a page? Thanks!

If you're using jQuery, you could run something like this
$('h2').each({
/* function */
});
Then to append to the .nav container you can run
$('h2').each(function() {
$('.nav').append($(this).text())
});

Use document.getElementsByTagName to select all the h2s:
var h2s = document.getElementsByTagName('h2');
for(var i = 0, length = h2s.length; i < length; i++){
// Do something with
h2s[i].innerHTML;
}

First of all, create an empty collection for the links you're going to create:
var $links = $();
Then, loop through each h2 using .each(), providing index and h2 as arguments — the first keep count, the second to get a reference of the current <h2> we're dealing with.
$('h2').each(function(index, h2){
// If there is no id (to link to), create one based on the index
if(!h2.id){
h2.id = 'header' + index;
}
// Get a jQuery object of the header
var $h2 = $(h2);
// Link will be an <a> with the same text as the heading, and will link to its id
var $link = $('<a>').text($h2.text()).attr('src', '#' + h2.id);
// Add this link to the collection
$links = $links.add($link);
});
So now $links contains your table of contents. Assuming you want to chuck these links in after the <h1>, you'd do the following:
$links.insertAfter('h1');
…but of course you can do whatever you want with them at this point.

Related

Trim tweets from plugin

I am using this Wordpress plugin
https://smashballoon.com/custom-twitter-feeds/demo
I would like to trim the Tweets to 120 characters.
I have no JS skills and very little php - I tried this which I found but I don't know if it's relevant at all.
$twitter_feed = (strlen($twitter_feed) > 120) ? substr($twitter_feed,0,10).'...' : $twitter_feed;
enter code here
I also attempted to edit my working code for trimming my post titles to suit which did not work.
function custom_trim_my_tweet( $twitter_feed ) {
global $uncode_vc_index;
if ( is_singular() && !$uncode_vc_index )
return $twitter_feed;
$twitter_feed = wp_trim_words( $twitter_feed, 9 );
return $twitter_feed;
}
add_filter( 'ctf-tweet-text', 'custom_trim_my_tweet' );
To trim the text using JavaScript:
First you have to select the element using a css selector. It's easiest if you can select the elements using an element id, like so:
var tweet = document.getElementById("my_tweet_id");
Then you can grab the text content of the element with element.innerText
var tweetText = tweet.innerText;
Then you can simple cut the length of the text inside the element using string.substring()
tweet.innerText = tweetText.substring(0, 120);
I honestly think you should try to fix this at the plugin/wordpress/php level rather than cutting text in JavaScript. But if that's what you want to do, then the above methos would work.
EDIT:
In case the tweet elements do not have unique ID's you will have to select all of them and then loop through each and perform the text-cutting. I'll give you an example of how to do that:
You might have to be a bit creative with your css selectors depending on how the tweets are displayed.
In my example I will assume that you have a div with the ID 'tweets' that then holds five separate div elements, one for each tweet, that all have the same class of 'single-tweet'.
First we get all the 'single-tweet' elements:
var tweets = document.querySelectorAll('#tweets .single-tweet');
tweets now contain a node list of the five 'single-tweet' divs.
Then we loop through them with .forEach() and do the text-cutting on each element.
tweets.forEach( (tweet) => {
tweet.innerText = tweet.innerText.substring(0, 120);
})
Now all of the 'single-tweet' elements will contain what's left after you cut the text down to 120 characters.

How to determine the img source using Jquery/Javascript on pageload?

I've gone through many SO threads, I can't seem to find a working solution.
All I'm trying to do is when the page loads, the site pushes all elements with the ".home" class into the array arr. Then, the script parses through each element in the array and tries to match it with a string. For example, right now all I have is a check to see if the element has the words "Boston" in it, in which case I want to make the image source for ".homeimage" the linked imgur link. I'm aware it's not wise to host images on imgur for these reasons, I'm just trying to check if it works. Below this test I have some redundant code I was practicing with that I found in a SO thread, changing the color of text to gray. I figured changing attributes is the same.
my html code:
<td colspan = "3"width=400px class = "home"><b><%= game.home %></b></td>
<td colspan = "3"><img style="width:150px;height:128px;" class = "homeimage"></td>
my javascript/jquery code:
<script>
var arr=[];
$(document).ready( function(){
$(".home").each(function(){ arr.push($(this));});
for(i = 0; i < arr.length; i++){
if(arr[i].indexOf "Boston" != -1){
$('.homeimage img').attr("src","http://i.imgur.com/s5WKBjy.png");
}
}
$.each(arr,function(key,val){
val.css('color','gray')}); //something redundant i was testing out
});
</script>
additional questions:
When I have multiple image with the .homeimage class, and multiple checks to determine the image source, will it make all of the images in the .homeimage class that src at the end? So whatever the last image that gets checked is the image src for all of the images with the ".homeimage" class? I don't want that. How can I uniquely make each image? Make a custom id instead of a class for each div? Also, does this script have to be below the html in question? Or does that not matter
Thanks for the future advice you all.
// I don't quite understand what you want to do.
// Since you type too much, and make no highlights.
// but here are somethings I found:
var arr = []; // this array is going to contain all tags (like td) with class '.home'
if(arr[i].innerHTML.indexOf("Boston") != -1) { } // indexOf() won't work on DOM element
// then arr[0] must be a DOM element, so why you call .indexOf("Boston") on it?
// next, $('.homeimage img') all return DOM element with class 'homeimage' or with tagName 'img'
$('img.homeimage'); // this may what you want to do.
// Alright, I try to give you an answer.
// this oImgUrl works as a map from some ((String))-->((img url))
var oImgUrl = {
'Boston': 'http://another.imageurl.com/boston.png',
'NewYork': 'http://another.imageurl.com/newyork.png'
};
// I take your "arr" unchanged
// this will test every element in arr
// if carry String like 'Boston' or 'NewYork'
// then find the img tag (img.homeimage) in it.
// then apply URL string to img tag
for (var i=0, length=arr.length; i < length; i++) {
if(arr[i].innerHTML.indexOf("Boston") != -1) {
arr[i].find('img.homeimage').attr('src', oImgUrl['Boston']);
continue;
}
if(arr[i].innerHTML.indexOf("New York") != -1) {
arr[i].find('img.homeimage').attr('src', oImgUrl['NewYork']);
continue;
}
}
example html:
<td class='home'>Welcome to Boston!<img class='homeimage'></td>
<td class='home'>Welcome to New York!<img class='homeimage'></td>
answers:
Question 1: Custom ID?
JavaScript will find these two td.home and add them into arr.
then, apply different image url to img tag
according to innerHTML of the td tag.
when doing this, you don't need to set each img tag an unique ID.
Question 2: Script place below html?
No, you don't have to.
You hold all thses script in docuement ready function
so, they will only work when HTML DOM is ready.
in another words, no matter where you place this script,
they will be invoked after Every Tag is ready.

Copy divs with certain id's to targets with related id's

How do I copy the content from all divs with a certain class or a certain beginning of an id to a bunch of divs with related id's? The examples I found didn't go through multiple copies. I have a solution that is working ok but instead of calling each copy with the id I would like to make the logic better.
Here's what I have now.
HTML (handlebars template)
<!-- the id comes from handlebar content. There are many like this -->
<pre><code id="target-example-01" class='language-markup'></code></pre>
<!-- this content is put to place once handlebars has rendered the page -->
<div id="code-examples" style="display: none;">
<div class='code-example' id="source-example-01">
this is my a code example... there are many like me...
</div>
</div>
Javascript
var source = document.getElementById('source-example-01').innerHTML;
var target = document.getElementById('target-example-01');
if (target) target.innerHTML=source;
This works ok but I have 100 examples so I wouldn't like to have 300 lines of code to manually maintain just to copy the content. How do I go through all the divs with "code-example" class and copy their content to divs with a matching id. All the source divs will have the id="source-(example-identifier)" and all the target divs will have the id="target-(example-identifier)". I guess the class wouldn't be needed if the code would go through all items with the id beginning with "source-"
I would be old school and stick with using getElementsByClassName() but since the question is how to target divs will have the id="target-(example-identifier) you can use querySelectorAll()
document.querySelectorAll('div[id^="source-example-"]')
for more information about querySelectorAll()
Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.
So the output is very much like using getElementsByClassName()
If you have any questions please leave a comment below and I will reply as soon as possible.
How to target a specific tag with a class and id?
document.querySelectorAll('div.code-example[id^="source-example-"]')
You will still need to loop through the contend just like you would for returning elements by class name but this query selector will only return div elements with the class name code-example and contains source-example- in the id attribute.
function QuerySelector() {
var Selector=document.querySelectorAll('div.code-example[id^="source-example-"]');
for(var i=0; i<Selector.length; i++){
alert(Selector[i].innerHTML);
}
}
<div class="code-example" id="source-example-01">Content Line One. - with class and id </div>
<div class="code-example">Content Line Two. - with correct class but no ID</div>
<div class="code-example" id="source-example-02">Content Line Three. - with class and id </div>
<button onclick="QuerySelector()">Get</button>
I hope this helps. Happy coding!
How do I go through all the divs with "code-example" class and copy
their content to divs with a matching id
Assuming that index of code-example elements is same as that of targets, then try
var allCodeExamples = document.getElementsByClassName( "code-example" );
for ( var counter = 0; counter < allCodeExamples.length ; counter++ )
{
var index = ("0" + counter).slice( -2 );
var target = document.getElementById( "target-example-" + index );
target.innerHTML = allCodeExamples[counter].innerHTML;
}
You can make use of data attributes for this using jquery:
<!-- the id comes from handlebar content. There are many like this -->
<pre><code id="target-example-01" class='language-markup'></code></pre>
<!-- this content is put to place once handlebars has rendered the page -->
<div id="code-examples" style="display: none;">
<div class='code-example' id="source-example-01" data-target="#target-example-01">
this is my a code example... there are many like me...
</div>
</div>
$(function(){
var targetId;
$(".code-example").each(function(){
targetId = $(this).attr("data-target");
$(targetId).html($(this).html());
});
});
I realised it makes more sense to check which examples are on the page and fetch the content for their source id's. I added another class to the code-tags "target-example"
Here's the javascript (jquery would probably make it nicer looking)
var examples = document.getElementsByClassName('target-example');
var i;
var id;
for (i = 0; i < examples.length; i++) {
id = examples[i].id;
var source = document.getElementById('source-'+id).innerHTML;
if (source) examples[i].innerHTML=source;
}

Change Anchor Target based on Text using JavaScript (No jQuery)

I have c# code which generates Anchor tags on fly. I wanted to change some of anchor tag target based on its text.
For example dynamic code generated HTML like below
<a target='_blank' class=txt href="http://www.stackoverflow.com">THE BEST SITE</a>
I wanted to change its target if text equals THE BEST SITE
Note: I have no jQuery files included in asp.net project.
So far I have tried including this script just to get the text, but it is not even displaying the alert
$(document).ready(function() {
$(".txt").click(function() {
alert($(this).text());
});
});
Here is a function that checks if an element's innerText is equal to a specific phrase. If it is, it sets the target attribute specific to that phrase.
function changeTarget(elem, phrase){
if(elem.innerText === phrase){
elem.target = phrase;
}
}
Depending on your DOM, you could just iterate through all your anchor elements and run this function with the desired phrase.
If you have a bunch of these with the .txt class you can just do something like:
var elems = document.querySelectorAll('.txt');
for(var i = 0; i < elems.length; i++){
changeTarget(elems[i], "THE BEST SITE");
}
I think you want something like
var els = document.getElementsByClassName('txt');
for(var i=0; i<els.length; ++i)
if(els[i].textContent == "THE BEST SITE")
els[i].target = 'something';

Find the first element of different span

I'm actually creating a script for a webpage.
I have not the possibility to modify the actual markup.
Here is the HTML Source Code :
<span id="spnTrNdCnt">
<span class="fufw" fldrnm="ibx" id="spnFldrNm">IBX</span>
<span id="spnUC">‎(
<span id="spnCV">2</span>
)‎</span>
</span>
I want to get the textContent for the span id equals spnCV.
The problem is that this code is present many times in the HTML Page. So each time i try to get the textContent (document.getElementById('spnCV').textContent) it gives me the last value of the last item.
I would like to know if there is any way to get the value of this first item (the first span which have the id spnCV) !
Thanks a lot for any kind of help.
querySelectorAll should in theory work for CSS selectors, which don't care about the restriction regarding unique ids.
var spans = document.querySelectorAll('#spnCV');
var length = spans.length;
for (var i=0; i<length; i++) {
console.log('Span ' + i, spans[i].textContent);
}
Working JsBin: http://jsbin.com/oriSiNa/1/edit
EDIT:
Since you only need the first span, then it's even easier:
var value = document.querySelector('#spnCV').textContent;
working demo fiddle
var ele = document.getElementsByTagName('span');
for(var i=0;i<ele.length;i++)
{
if(ele[i].id=='spnCV')
{
// when i=0 it will be the first node
// do something
var text = (ele[i].innerText || ele[i].textContent);
alert(text);
}
}
ID's must be unique as is mentioned before, but since you cannot change the source, please check out firstchild, assuming that you can add some js somehow.

Categories

Resources