I'm looking for a way to search for any links that have an href of "#" and change the CSS styling of them to make those links a different color. Essentially, I want to be able to easily identify which links are broken and which aren't.
This is being used for a massive documentation project, and not all of the files are uploaded yet. I want users to be able to easily identify which links work and which won't. Is this able to be done with Javascript somehow?
You need to loop through all the links on the page, checking them individually and changing the style if required. Here's a starting point for you to expand from:
var anchors = document.getElementsByTagName('a'); //Get all the links
for(var i = 0; i < anchors.length; i++) { //Loop through links
if(anchors[i].href === '#') { //If link points to "href",
anchors[i].style.color = 'red'; //then change the link's color to red
}
}
in javascript you can do somehow like following:
var els = document.getElementsByTagName("a");
for (var i = 0, l = els.length; i < l; i++) {
var el = els[i];
if (el.href === '#') {
//do something here
}
}
I think that's the wrong approach. You should probably have a server-side process that parses your files and fixes/identifies the broken links rather than doing it at runtime using JavaScript.
However, you can query elements based on their href attribute using document.querySelectorAll.
[].forEach.call(document.querySelectorAll('a[href="#"]'), function (link) {
link.style.color = 'red'; //change style
});
I know this is an old question, but this question needs an answer that doesn't require JavaScript - styling links based on their href with pure CSS is much more efficient.
This CSS styles all links with an href of "#" red:
a[href="#"] {
color: red;
}
Related
Since I'm still learning the localStorage and cookie techniques, I am trying to change the color of the div on page1.html from page2.html by using the submit button, color of the div should be changed permanently when the user clicks submit button on page2.html
This is what I got on page1:
window.onload = function() {
var anchors = document.getElementsByClassName("circleBase type1");
for(var i = 0; i < anchors.length; i++) {
anchors[i].onclick = function() {
window.open("EnterInformation.html");
}
}
}
on page2 i used localStorage for saving data permanently, with this save I need to change the color of the div on page1.
This is page2 so far:
function SaveInfo() {
localStorage.Yritys = $('#Yritys').val();
localStorage.Henkilönimi = $('#Henkilönimi').val();
localStorage.Asema_yrityksessa = $('#Asema_yrityksessa').val();
localStorage.Puhelin_Nr = $("#Puhelin_Nr").val();
localStorage.e_Mail = $('#e_Mail').val();
localStorage.Keskustelun_aihe = $('#Keskustelun_aihe').val();
What would be the solution to this? It would be nice to use localStorage instead of cookies. Thank You!
You can create a local storage
myCustomColor = '#2B2A28';
localStorage.setItem('myDataStorage', myCustomColor);
Then retrieve them
var myLoadedColor = localStorage.getItem('myDataStorage');
document.getElementById('myDiv').style.backgroundColor = myLoadedColor;
myDataStorage is the name of your created localStorage. You can use different names to create multiple localStorages if you would.
You can .getItem on the localStorage upon page load and then set the color of your div based on that localStorage data.
var x = document.getElementsByClassName("example");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
This little piece of code scans your page for all elements with the matching class and changes the background color then. Of course you can use it also for single elements:
var x = document.getElementByClassName("example");
x.style.backgroundColor = "red";
But in this case JavaScript will only change the first div it finds with a matching class.
To sum it up: There is no other convenient way than marking/tagging your elements in a way that they are unique and recognizable. Normally this is done by the name or the id. Class would also work but is seldomly used in this way.
Well, actually you could also iterate through the DOM and count the elments in order to change let's say the 15th div that appears. But what if you add additional divs a couple of days later? It's a very uncomfortable approach.
Use the localStorage and it will work using names or ids. You only have once to give every div it's id and/or name.
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';
I am trying to write a function for an extension that can find a link inside a specific div and click it. The link has no id or class name, so I was looking for something similar to a CSS selector but with JS without using '$' or 'jQuery' since that will require me to embed a jquery library with the extension.
The div has a class name and then a link inside, so this is the code I have so far --
function COut() {
var a = document.getElementsByClassName('bottom_row').getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
var elem = a[i],
elem.click();
}
}
This the markup for the div and link -
<div class="bottom_row">
<a onclick="miniAddToCart.closeMiniAddToCart({cmConversionEvent: 'Checkout'})" href="http://www.domain.com/shoppingcart/default.cfm?checkout=1&"><img src="http://www.domain.com/images/eb/minicart/checkout.gif" alt="Checkout"></a>
</div>
Any ideas what Im doing wrong?
getElementsByClassName('bottom_row').getElementsByTagName('a');
getElementsByClassName returns a set, not a single item
getElementsByClassName('bottom_row')[0].getElementsByTagName('a');
^^^
If there can be more than one item with the className, than you will need to loop. And if you support modern day browsers, you can look into querySelectorAll
And finally clicking on a link is not as easy as calling click()
How can I simulate a click to an anchor tag?
If you want it to do to the url, you might be better off just setting window.location.href
If there is a single A tag, I won't prefer to make loop for that. Instead you can just do it like:
function COut() {
var a = document.getElementsByClassName('bottom_row')[0].getElementsByTagName('a')[0];
if(a){
a.click();
}
}
for(var i=0; i< vendors.length;i++)
{
var $ul = $("<ul>").attr("data-role", "listview")
.attr("data-divider-theme","a")
.attr("data-inset","true")
.appendTo("#vendorLists");
$("<li>").attr("data-role", "list-divider")
.attr("role","heading")
.text(vendors[i])
.appendTo($ul);
for(var j=0; j<coupons[i].length; j++)
{
var x = coupons[i][j].split(":");
var $li = $("<li>").attr("data-theme", "a")
.appendTo($ul);
$("<a>").text(x[0] + ":" + x[1])
.appendTo($li);
}
}
I am using this code to create a list dynamically by fetching from a array.
vendorList is a div tag
The Jquery isnt coming on these..only the text is being displayed
Plz help
You mention vendorList is a div tag. However, you use appendTo("#vendorLists") in your definition of $ul. Unless you meant vendorLists is a div tag, then you want to use appendTo("#vendorList") instead.
Each time you add a dynamic content to the jQuery Mobile page you need to trigger a specific function meant to enhance page markup.
In your case it is this function:
$('[data-role="listview"]').trigger('refresh');
If you want to read more about that (with live jsFiddle examples) take a look at my other ARTICLE about this topic. Or it can be found HERE.
I know how to find all the links but I do not know how to programmatically inject html after a tag. I think the html should end up like this:
<a href="http:www.google.com> this is a useful website</a> <input type="checkbox" name="option" >
You can do this simply in JQuery, using after:
$("a").after("<input type='checkbox' name='option' />");
Edit
Inspired by RobG's comment -- to apply to only specific links, change the selector:
// select all a-tags that link to Google
$("a[href='http://www.google.com']")
Or use a wildcard of some kind:
// select all a-tags that contain any href tags (ie, exclude anchor tags)
$("a[href]")
Or you can do this with plain JavaScript (though jQuery definitely simplifies your task):
var links = document.getElementsByTagName('a');
for (var i = 0, len = links.length; i < len; i++) {
var chk = document.createElement('input');
chk.type = 'checkbox';
chk.value = links[i].textContent || links[i].innerText; // or whatever...
chk.name = chk.value.replace(/(\s+)/g, ''); // or whatever...
links[i].parentNode.insertBefore(chk, links[i].nextSibling);
}
If, as raised in the comment to dbaseman's answer, you're using some of the a elements as anchors, you should consider using ids on existing elements as the targets for internal navigation, since an empty, though named, a is a pretty old technique, and even IE supports the use of ids now.
However if change is not possible the above can be changed to incorporate an if check:
var links = document.getElementsByTagName('a');
for (var i = 0, len = links.length; i < len; i++) {
if (links[i].href) {
var chk = document.createElement('input');
chk.type = 'checkbox';
chk.value = links[i].textContent || links[i].innerText; // or whatever...
chk.name = chk.value.replace(/(\s+)/g, ''); // or whatever...
links[i].parentNode.insertBefore(chk, links[i].nextSibling);
}
}
Further, if you wish to refine the a elements to those contained within a given element, simply use a specific node in place of document in the first line:
var links = document.getElementById('onlyInThisElement').getElementsByTagName('a');
Where first you retrieve the node with an id of onlyInThisElement and then search only within that div for the a elements.
You can get all the links in a page using the links collection. You can then easily append a checkbox by looping over the collection and using insertBefore and nextSibling or whatever jQuery equivalent you wish to use.
Note that the links collection only includes A elements with a HREF attribute, it will not include anchors (i.e. A elements with a NAME or ID an no HREF).