New to Javascript. How can I search a page for text in a certain "p class" and click on the href link next to it? Trying to create a Chrome extension that will open a Twitter link in a new tab. I have a basic extension but stuck here. Any help is greatly appreciated.
How would I find the first href that mentions the Patriots (or any keyword) from a tweet?
HTML of a tweet:
<p class="js-tweet-text tweet-text">
'No chance' Patriots franchise tag Aqib Talib
<a href="http://t.co/6dV3EHg5WU" rel="nofollow" dir="ltr" data-expanded-url="http://dlvr.it/4tsL8d" class="twitter-timeline-link" target="_blank" title="http://dlvr.it/4tsL8d">
<span class="tco-ellipsis"></span>
<span class="invisible">http://</span>
<span class="js-display-url">dlvr.it/4tsL8d</span>
<span class="invisible"></span>
<span class="tco-ellipsis">_</span>
</span></a></p>
You can use querySelectorAll() to find the items to search, do the search in the content yourself and then follow the DOM to get the href from the next link:
function findTextAndClick(findText) {
var items = document.querySelectorAll(".tweet-text");
for (var i = 0; i < items.length; i++) {
var text = items[i].textContent || items[i].innerText;
if (text.indexOf(findText) >= 0) {
var links = items[i].querySelectorAll("a");
if (links.length) {
window.location = links[0].href;
return;
}
}
}
}
Sample usage on your HTML:
findTextAndClick("Patriots");
Related
I have a JavaScript array and I wanted to put HTML links in that array. I don't know if there is a certain way to go about this. Also, if it's possible, when the user clicks the button and it selects the link, is there a way to make that link open up in a new tab (I know in HTML its target=_blank). I appreciate any help as always.
JavaScript:
var i = Math.floor(Math.random() * 10) +1;
function randomPageWithJS() {
const arrayJS = [link1, link2, link3, link4];
document.getElementById('randomPageWithJS').value = arrayJS[i];
}
randomPageWithJS();
HTML:
<form>
Random Song:<input type="text" id="randomPageWithJS" name="randomPage"/>
<input type="button" value="RandomPage" onclick="randomPageWithJS()" width="1000"/>
</form>
Use window.open
window.open(arrayJS[i], '_blank');
Example:
function randomPage() {
const links = ['https://google.com', 'https://stackoverflow.com', 'https://stackoverflow.com/questions/56139010/'];
window.open(links[Math.floor(Math.random()*links.length)], '_blank');
}
<input type="button" value="Random Page" onclick="randomPage()">
In some part of an html page, I have a link with the following code :
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
I would like to automatically display the same link in another part of the same page by using a javascript.
What would be the script to insert in my page ?
Thank you in advance for any help in this matter.
Patrick
Try this:
myVar = document.getElementById("idname");
varLink = (myVar.attributes.href);
As son as you know the target id:
<div id="targetID">New Link: </div>
<div id="targetID2">New Link 2: </div>
And If you are using jQuery you can do like this:
var link = $("#idname").clone();
link.attr("id",link.attr("id") + (Math.random() * 10));
$("#targetID").append(link);
If not:
var link = document.getElementById("idname");
var newLink = document.createElement("a");
newLink.href = link.href;
newLink.className = link.className;
newLink.innerHTML = link.innerHTML;
newLink.id = link.id + (Math.random() * 10);
document.getElementById("targetID2").appendChild(newLink);
See this Example
<script>
window.onload = function() {
// get data from link we want to copy
var aHref = document.getElementById('idname').href;
var aText = document.getElementById('idname').innerHTML;
// create new link element with data above
var a = document.createElement('a');
a.innerHTML = aText;
a.href = aHref;
// paste our link to needed place
var placeToCopy = document.getElementById('anotherplace');
placeToCopy.appendChild(a);
}
</script>
Use code above, if you want just to copy your link to another place. JSFiddle
First, I want to point out that if you will just copy the element that will throw an error because the copied element will have the same id of the first one, so if you will create a copy of your element you don't have to give it the same id.
Try this code:
function copyLink(newDestination){
var dest=document.getElementById(newDestination);
var newLink=document.createElement("a");
var myLink=document.getElementsByClassName("classname")[0];
newLink.href=myLink.href;
newLink.className = myLink.className;
newLink.innerHTML = myLink.innerHTML;
newDestination.appendChild(newLink);
}
The newDestination parameter is the container element of the new Link.
For example if the new Container element has the id "div1":
window.onload = function() {
copyLink(div1);
}
Here's a DEMO.
Thank you very much to everyone for so many prompt replies.
Finally, I was able to use Jquery.
So, I tried the solution given by Andrew Lancaster.
In my page, I added the codes as follows, in this order :
1-
<span id="span1">
<a class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
and further down the page :
2-
<script type="text/javascript">
var span1val = $('#span1').html();
$('#span2').html(span1val);
</script>
Therefore, the two expected identical links are properly displayed.
But, unfortunately, I forgot to say something in my initial request:
the original link is in the bottom part of my page
I would like to have the duplicated link in a upper part of my page
So, would you know how to have the duplicated link above the original link ?
By the way, to solve the invalid markup mentioned by David, I just deleted id="idname" from the original link (that I could ignored or replaced by other means).
Thank you again in advance for any new reply.
Patrick
Using Jquery you could wrap your link in a span with an ID and then get the value of that ID and push it into another span id.
HTML
<span id="span1">
<a id="idname" class="classname" href="www.MySite.com/image-name.jpg">link-text</a>
</span>
<p>
<span id="span2"></span>
</p>
jQuery
var span1val = $('#span1').html();
$('#span2').html(span1val);
Example can be found here.
http://jsfiddle.net/3en2Lgmu/5/
I have a messages page where i can see them as a list. If i select each one of them, I display them in the right side of the page. For that, I have two javascript functions for "next" and "previous" buttons for the messages' page. So I have a list of messages on the screen, if I click "next", I see the next page of messages and so on.
Everything work allright, the only problem is in Chrome, it wouldn't load the page number in a span section on the bottom of the page. This is the function for next page:
$("#next").click(function() {
var currentPageElem = $("#currentPage");
var totalPagesElem = $("#totalPages");
var minItemElem = $("#minItem");
var maxItemElem = $("#maxItem");
var totalItemsElem = $("#totalItems");
var itemsOnPageElem = $("#itemsOnPage");
var currentPageValue = parseInt(currentPageElem.val(), 10);
if (currentPageValue < totalPagesElem.val()) {
currentPageElem.val(currentPageValue + 1);
}
//the first record on the current page
minItem = $(this).getMinItem(currentPageElem.val(), itemsOnPageElem.val());
minItemElem.val(minItem);
//the last record on the current page
maxItem = $(this).getMaxItem(currentPageElem.val(), itemsOnPageElem.val(), totalItemsElem.val());
maxItemElem.val(maxItem);
$(this).showItems(minItem, maxItem);
var pageHtml = $(".pages").html();
$(".pages").html($(this).newPageHtml(pageHtml, currentPageElem.val()));
}); });
$.fn.newPageHtml = function(pageHtml, currentPage) {
var idx1=pageHtml.indexOf("Pagina ");
var idx2=pageHtml.indexOf(" / ");
var prevPage = pageHtml.substring(idx1 + 7, idx2);
return pageHtml.replace(prevPage, currentPage);
};
This is the html code that involves the js:
<input type="hidden" id="totalPages" name="totalPages" value="${totalPages}"/>
<input type="hidden" id="currentPage" name="currentPage" value="${currentPage}"/>
<input type="hidden" id="minItem" name="minItem" value="${minItem}"/>
<input type="hidden" id="maxItem" name="maxItem" value="${maxItem}"/>
...
<div class="controls">
<a class="prev" id="prev"></a>
<a class="next" id="next"></a>
<span class="pages">
<fmt:message key="messages.page">
<fmt:param>${currentPage}</fmt:param>
<fmt:param>${totalPages}</fmt:param>
</fmt:message></span></div>
are you try in firefox or safari?
what is your java version?
are you review in about:config if you have enable java/javascript in Chrome
I have solved the problem. There was an issue with the CSS files that wouldn't allow the text to transform correctly in Google Chrome. So I modified the style of the span class from above like this:
<span class="pages" style = " position: absolute; ">
Initially, the position of the span class was relative. I think Chrome has a problem with this type of CSS.
I'm trying to replace every instance of "Administrator" on my page with "Admin" Or something similar to that. How would I replace that? If it helps, the span is inside an tag that has the class "user-title".
Like this page but I kinda need to be fed the answer. This is my first time working with javascript.
<ul class="author-ident">
<li class="username">
<a title="Go to Different55's profile" href="http://fwin.co.cc/pun/profile.php?id=2">Different55</a>
</li>
<li class="usertitle">
<span>Administrator</span>
</li>
<li class="userstatus">
<span>Online</span>
</li>
</ul>
I work mostly with JQuery so I can only give you a JQuery solution of the top of my head. Sorry if this is not an option for you. With JQuery you could do this...
$(".user-title").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
NOTE: If you expect more than one instance of "Administrator" per span tag then you will need to do a regex replace like follows...
.replace(/Administrator/g, "Admin");
See this for more info on the regex flag (e.g. "g" means global - more than one)
EDIT: Here is a javascript version....
var spans = document.getElementsByClassName("user-title");
for (var i = 0; i < spans.length; i++)
{
spans[i].innerHTML = spans[i].innerHTML.replace(/Administrator/g, "Admin");
}
ANSWER: This is based on your provided sample HTML (note that I have changed the class name "usertitle" based on your html, check if this is correct)...
var parents = document.getElementsByClassName("usertitle");
for (var i = 0; i < parents.length; i++)
{
var spans = parents[i].getElementsByTagName("span");
for(var j = 0; j < spans.length; j++){
spans[j].innerHTML = spans[j].innerHTML.replace(/Administrator/g, "Admin");
}
}
The JQuery equivalent...
$(".usertitle span").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
<script type="text/javascript">
function changeText(){
document.getElementById('anId').innerHTML = 'my friend';
}
</script>
<p>Welcome to the site <b id='anId'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
This will change the content of that .
You can run JS that will look in every span and, if you find "administrator", that you can be use that snippet of code.
To do the replacement you mentioned (replacing all occurrences of Administrator with Admin inside all spans inside .user-title, use:
$('.user-title span').each(function() {
$(this).html($(this).html().replace(/Administrator/g, 'Admin'));
});
NOTE: Assuming you are using jQuery in your app
You can use this function :
function correct() {
var a = document.getElementsByClassName("user-title");
var i = 0;
for(i=0; i<a.length; i++) {
while((a[i].innerHTML).indexOf("Administrator") >= 0){
a[i].innerHTML = a[i].innerHTML.replace(/Administrator/g, 'Admin');
}
}
}
this function will get collection of all elements having class name as "user-title". then the n in for loop, we will access each element in collection, see if it's innerHTML has the word that you want to replace and if it has, we replace it.
Put all instances of the word "Administrator" into a <span> with a certain class, f.i.:
<span class="user_type">Administrator</span>
Then you can use jQuery to do:
$("span.user_type").html("Admin");
Note that this may not be the nicest thing to do but we don't have any other details on what you're trying to accomplish.
I hope somebody can help me... I try to grab a parameter, which is saved in the head of a html-site, and add this parameter to all links on the site, which have no "rel='gallery'"-attribut. some links have allready other GET-parameters. It looks like this:
<head>
<script type="text/javascript">
var ParameterNew = "test";
</script>
</head>
[...]
Search: Google<br/>
Social Media: Facebook
<br/><br/>
<a rel="gallery" href="img/1.jpg">Gallery Link 1</a><br/>
<a rel="gallery" href="img/2.jpg">Gallery Link 2</a><br/>
So I try to append the ParameterNew behind all links, which have no rel-attribut.
At the end it has to looks lie this:
<head>
<script type="text/javascript">
var ParameterNew = "test";
</script>
</head>
[...]
Search: Google<br/>
Social Media: Facebook
<br/><br/>
<a rel="gallery" href="img/1.jpg">Gallery Link 1</a><br/>
<a rel="gallery" href="img/2.jpg">Gallery Link 2</a><br/>
I wrote this one. It only replace the innerHTML (such as an example):
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].target !== "_blank")
links[i].innerHTML = 'test';
}
I only have problem to append the parameter... Maybe someone can help? thanx
This is a reasonably simple solution that takes into account your exact example conditions. That is, it assumes you have simple links so that all that needs to be done is check which connector to use in adding the parameter. If your links can contain parameters that are links, you'll need to do something more complex to figure out whether to use a ? or & to append the parameter.
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
if (links[i].rel != 'gallery') {
var href = links[i].href,
connector = '?';
if (href && href.match(/\?/)) {
connector = '&';
}
links[i].href = href + connector + 'parameter=' + ParameterNew;
}
}