Does anyone know how to exclude specific links from the random_all javascript generator.
I have an archive blog page with a list of links, where I am creating a random button. However, the random link script below takes ANY links from the page. I would like to exclude a few links so that they wouldn't be included as a possibility in the script ( for instance: my home page, or contact page ... just the blog posts displayed on the page)
http://www.eointhomassharkey.com/tester - page can be found here
<script>
function random_all(){
var myrandom=Math.round(Math.random()*(document.links.length-1))
window.location=document.links[myrandom].href
}
//-->
</script>
Any help is greatly appreciated.
-Eoin Thomas
First, since Math.random() gets a number between 0 and .9 repeating (never 1), you want change that to a logical expression. Then you run a loop... or better yet, make an inArray function. If there aren't too many exclusions then you can use recursion.
//<![CDATA[
/* external.js */
var doc, bod, I, inArray, randLinker, old; // for use on other loads
onload = function(){
if(old)old(); // change old var if using technique on other pages
doc = document; bod = doc.body;
I = function(id){
return doc.getElementById(id);
}
inArray = function(v, a){
for(var i=0,l=a.length; i<l; i++){
if(a[i] === v){
return true;
}
}
return false;
}
randLinker = function(){
var exclude = [].slice.call(arguments), lnx = doc.links;
var randLink = lnx[Math.floor(Math.random()*lnx.length)];
var randHref = randLink.href;
if(randLink === this || inArray(randHref, exclude)){
return randLinker.apply(this, exclude);
}
this.href = randHref;
}
I('frm').onsubmit = function(){
return false;
}
var rand_link = I('rand_link');
rand_link.onclick = function(){
randLinker.call(this, 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting', 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions');
}
}
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#ccc; padding:20px; margin:0 auto;
}
#frm>a{
float:left; clear:left;
}
.cb{
clear:both;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>Random Link</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='frm' name='frm'>
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration'>Loops and iteration</a>
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions'>Functions</a>
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators'>Expressions and Operators</a>
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates'>Numbers and dates</a>
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Text_formatting'>Text formatting</a>
<a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions'>Regular Expressions</a>
<a id='rand_link' href=''>Random Link</a>
</form>
<div class='cb'></div>
</div>
</body>
</html>
Note that randLinker takes any amount of arguments. Every one will be excluded. Make sure to call this function in the context of the random link.
What I would recommend doing is setting up an array of pages / sites that you wish to exclude. Then you can run your code that redirects (or runs console.log() in my example) inside of an if condition that checks that the array does not include the randomly-generated link's href value.
This can be done with the ES6 method includes(). Because you don't want the array to include the value, you simply need to check that includes() returns false.
This can be seen in the following, where the logic will only trigger for StackOverflow and Twitter:
var exclusions = ['http://www.facebook.com/', 'http://www.google.com/']
function random_all() {
var myrandom = Math.round(Math.random() * (document.links.length - 1));
if (!exclusions.includes(document.links[myrandom].href)) {
//window.location = document.links[myrandom].href;
console.log(document.links[myrandom].href);
}
else {
console.log('The random link is on the exclusion list!');
}
}
random_all();
Facebook<br>
Google<br>
StackOverflow<br>
Twitter
Hope this helps! :)
This will filter out all blacklisted links from document.links and then randomize only whitelist:
var blacklist = ["javascript:random_all()", "https://google.com/"];
function random_all(){
var whitelist = Array.from(document.links).filter(item => !blacklist.includes(item.href));
if (whitelist.length === 0) {
alert('No whitelisted links!')
return;
}
// 0<->(whitelist.length-1)
var myrandom=Math.round(Math.random()*(whitelist.length-1))
console.log(whitelist[myrandom].href);
//window.location=whitelist[myrandom].href
}
Google
Stackoverflow
Github
Random
Related
I know that the <script> element can have function show(shown, hidden) on it. but with the 2 pages ({document.getElementById(shown).style.display='block'; document.getElementById(hidden).style.display='none'; return false;) in that, I can't figure out how to make that page count more. Any help?
P.S. I am open to almost anything. I can't guarantee your answers will help, but I might be able to figure it out using your suggestions.
I have tried more things on the function show(shown, hidden, hidden, hidden) but that does not help.
I am stuck. I have researched anything I could find. I can't figure it out.
Please help me.
My specific code I want suggestions on is this:
<script>
function show(shown, hidden) {
document.getElementById(shown).style.display='block';
document.getElementById(hidden).style.display='none';
return false;
}
</script>
with some <div>s.
I know this is probably not helping you figure out how to help me, but I need to know. (I hate full-on JavaScript!)
<!doctype html>
<html lang="en">
<head>
<title>Multi but Single Page</title>
<meta charset="utf-8">
<style>
.templates {
display: none;
}
</style>
<script>
// we save all templates in an global Variable
var templateStack = [];
// https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
function getParameterByName(name, url) {
url = url || window.location.href;
name = name.replace(/[\[\]]/g, '\\$&');
var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, ' '));
}
window.addEventListener('load', function (e) {
// get all hidden template elements
var templates = document.getElementsByClassName('templates');
for (var i = 0, v; v = templates[i]; i++) {
// each Child Node is a new Page
for (var j = 0, x; x = v.childNodes[j]; j++) {
// at least if it's an element
if (x.nodeType === Node.ELEMENT_NODE) {
templateStack.push(x);
}
}
}
// uri support ?page=1 loads Page 2 and ?page=0 loads Page 1, default is 0
var pageIndex = getParameterByName('page') || '0';
// so we can test it with a Browser by just insert 'loadPage(1)'
loadPage(pageIndex);
});
function loadPage(index) {
// only valid indexes
if (index >= templateStack.length || index < 0) {
document.body.innerText = '404 Page not found';
return;
}
// clean everything in our page
document.body.innerHTML = '';
// append our fetched Page out of our Global Variable
document.body.appendChild(templateStack[index]);
}
</script>
</head>
<body>
<div class="templates">
<div>
<h3>Page 1</h3>
<p>
Welcome to Page 1
</p>
Load Page 2
</div>
<div>
<h1>Page 2</h1>
<p>
Our Page 2
</p>
Back to Page 1
</div>
</div>
</body>
</html>
I understand that you can use it with 2 pages but when you want to make more pages like 4-5 pages?
First you need an clear function (it will hide all the pages)
In the clear function get the body in dom and get all the childrens then make a foreach loop hiding all of them
Second you need an show function which will use the page as an parameter like "show('page1');" it will first call the clear function and then show the page1
The script below is meant to find all html comments in the page (there are 4) and return them as one string. I ran the script below and received a "Too Much Recursion" error.
Have I created an infinite loop or did I do something else?
function findComment()
{
var olElement = document.getElementById("everything");//this is the id for my body element
var comments = new Array();
if (olElement.nodeType == 8)
{
comments[comments.length] = olElement;
} else if(olElement.childNodes.length>0)
{
for (var i = 0; i<olElement.childNodes.length; i++)
{
comments = comments.concat(findComment(olElement.childNodes[i]));
}
}
alert(comments);
}
//window.onload = countListItems;
//window.onload = countTagItems;
//window.onload = getElements;
window.onload = findComment;
This is a rough cut version of how you could do it with a recursion. It is not really elegant but will do the work:
function fico(el){
if (el.nodeType==8) return [el.textContent.trim()]
else return [...el.childNodes].map(fico);
}
console.log(fico(document.querySelector("#everything")).toString().replace(/,+/g,", "));
<body id="everything">
<div>something <!-- comment1 -->
<div>with something inside
<!-- comment2 -->
<div>and something further<div>
<span>inside
<!-- comment3 --></span>
it
</div>
more regular text
<!-- comment4 --> and enough.
</div></body>
Depending on the html input the function will return an array of subarrays with further levels of subarrays. To flatten it I used the Array-method toString() and then replace() with a regular expression to throw out the multiple commas in the result. There is still a superfluous one at the beginning ;-)
And here is an alternative version that uses a global comments array like you used in your code:
var comments=[];
function fico(el){
if (el.nodeType==8) comments.push(el.textContent.trim());
else [...el.childNodes].forEach(fico);
}
fico(document.querySelector("#everything")); // collect comments ...
console.log(comments.join(', ')); // ... and display them
<body id="everything">
<div>something <!-- comment1 -->
<div>with something inside
<!-- comment2 -->
<div>and something further<div>
<span>inside
<!-- comment3 --></span>
it
</div>
more regular text
<!-- comment4 --> and enough.
</div></body>
Move the olElements variable outside the function and pass in the element you want to search. The recursion you have is always starting with 'everything';
var comments = new Array();
function findComment(element)
{
if (element.nodeType == 8)
{
comments[comments.length] = element;
} else if(element.childNodes.length>0)
{
for (var i = 0; i<element.childNodes.length; i++)
{
comments = comments.concat(findComment(element.childNodes[i]));
}
}
return comments;
}
var olElement = document.getElementById("everything");//this is the id for my body element
alert(findComment(olElement));
Update: I tried both methods above and received error that either "element" or "el" is null. So...progress. I've pulled together my full code and html and posted below:
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page</title>
<script>
var comments = new Array();
function findComment(element)
{
if (element.nodeType == 8)
{
comments[comments.length] = element;
} else if(element.childNodes.length>0)
{
for (var i = 0; i<element.childNodes.length; i++)
{
comments = comments.concat(findComment(element.childNodes[i]));
}
}
return comments;
}
//window.onload = countListItems;
//window.onload = countTagItems;
//window.onload = getElements;
var olElement = document.getElementById("everything");//this is the id for my body element
window.onload = alert(findComment(olElement));
</script>
</head>
<body>
<div id="everything">
<h1>Things to Do</h1><!--this is a title-->
<ol id="toDoList"><!--this is a list-->
<li>Mow the lawn</li><!--this is a list item-->
<li>Clean the windows</li>
<li>Answer your email</li>
</ol>
<p id="toDoNotes">Make sure all these things are done so you can get some rest.</p>
</div>
</body>
</html>
I am working on the tablet's display of a Pepper robot; I have a functional HTML index page comprising a list of questions—each question redirects to its respective HTML when clicked on—, 2 volume buttons and 2 other buttons—one that pops up an instruction image and the other one that closes the index page and gets back to the splash screen, which when clicked upon, reveals the index page. So far everything is working. The issue is that when I click a question—I get redirected to its HTML page, but then I get stuck there, as neither the 2 volume buttons nor the 2 other buttons work;
I made sure to include the following in each HTML page:
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
I also reused the same JavaScript functions that worked for the index page.
I commented out some line:
btnPrevious.addEventListener('click', goToPreviousPage);
because I noticed it prevented the splash screen from disappearing when clicked on—i.e., the visibility attribute stays on visible instead of switching to hidden thus revealing the index page, but still, the 3 remaining buttons don't work anyway.
Here is my faq.js code:
/* global QiSession */
var serviceName = 'ADFAQ';
var volumeUpEvent = serviceName + '/VolumeUp';
var volumeDownEvent = serviceName + '/VolumeDown';
var volumeData = serviceName + '/Volume';
/* Clickable buttons */
var btnReturn = document.getElementById('return');
var btnHelp = document.getElementById('call_help');
var btnPrevious = document.getElementById('previous_page');
var btnVolUp = document.getElementById('volume-up');
var btnVolDown = document.getElementById('volume-down');
/* Help image and splash screen */
var helper = document.getElementById('helper');
var img = document.getElementById('click_on_me');
var memory;
var volume;
var audioDevice;
QiSession(connected, disconnected);
function connected (s) {
console.log('QiSession connected');
var questions = document.getElementById('questions');
/* Associating buttons to their respective functions */
btnHelp.addEventListener('click', showHelper);
btnReturn.addEventListener('click', closeQuestions);
//btnPrevious.addEventListener('click', goToPreviousPage);
btnVolUp.addEventListener('click', raiseVolume);
btnVolDown.addEventListener('click', lowerVolume);
img.addEventListener('click', loadQuestions);
questions.addEventListener('click', clickOnQuestion);
s.service('ALMemory').then(function (m) {
m.subscriber(serviceName + '/DialogEnded').then(function (subscriber) {
subscriber.signal.connect(hideQuestions);
});
m.subscriber(serviceName + '/Pepper').then(function (subscriber) {
subscriber.signal.connect(displayPepperHTML)
});
m.subscriber(serviceName + '/RaiseVolume').then(function (subscriber) {
subscriber.signal.connect(raiseVolume);
});
m.subscriber(serviceName + '/LowerVolume').then(function (subscriber) {
subscriber.signal.connect(lowerVolume);
});
memory = m;
});
s.service('ALAudioDevice').then(function (a) {
a.getOutputVolume().then(assignVolume);
audioDevice = a
});
}
function disconnected () {
console.log('QiSession disconnected');
}
function assignVolume(value){
volume = value;
}
function raiseVolume (event) {
var changed = 0;
if(volume < 100) {
volume = Math.min(volume + 5, 100);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeUpEvent, changed);
}
function lowerVolume (event) {
var changed = 0;
if(volume > 30) {
volume = Math.max(volume - 5, 0);
audioDevice.setOutputVolume(volume);
changed = 1;
}
memory.insertData(volumeData, volume);
memory.raiseEvent(volumeDownEvent, changed);
}
function showHelper (event) {
if (btnHelp.innerHTML === '?') {
helper.style.opacity = '1';
helper.style.zIndex = '1';
btnHelp.innerHTML = '←';
} else {
helper.style.opacity = '0';
helper.style.zIndex = '-1';
btnHelp.innerHTML = '?';
}
btnHelp.blur();
}
function loadQuestions (event) {
memory.raiseEvent(serviceName + '/LoadQuestions', 1);
img.style.visibility = 'hidden';
}
function goToPreviousPage () {
window.location.href = "index.html";
}
function displayPepperHTML() {
window.location.href = "pepper.html";
}
function closeQuestions (event) {
if(location.href != "index.html")
{window.location.href = "index.html";}
memory.raiseEvent(serviceName + '/CloseQuestions', 1);
btnReturn.blur();
}
function hideQuestions (data) {
if (data !== 0) {
img.style.visibility = 'visible';
helper.style.opacity = '0';
btnHelp.innerHTML = '?';
}
}
function clickOnQuestion (event) {
memory.raiseEvent(serviceName + '/' + event.target.id, 1);
}
Here is my non-functioning pepper.html code:
<!DOCTYPE html>
<html lang="fr">
<head>
<title>Pepper</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=1280, user-scalable=no" />
<link type="text/css" rel="stylesheet" href="css/style.css" />
<link type="text/css" rel="stylesheet" href="css/faq.css" />
</head>
<body>
<header>
<h1>Bla bla bla</h1>
<span class="buttons">
<button id="previous_page" class="button-help"> ← </button>
<button id="return" class="button-return">X</button>
</span>
<div id="helper" class="pop-up">
<img src="img/interactionscreen_frf.png" alt="Bla bla bla">
</div>
</header>
<ul id="questions">
<p>
Bla bla bla
</p>
<div class="volume-part">
<div id="volume-up" class="Click-me">+</div>
<img src="img/speaker.png" alt="Bla bla bla" style="vertical-align: middle;">
<div id="volume-down" class="Click-me">-</div>
</div>
</ul>
<script type="text/javascript" src="/libs/qimessaging/2/qimessaging.js"></script>
<script type="text/javascript" src="faq.js"></script>
</body>
</html>
Thank you for your help.
I am expecting the pepper.html page to respond to both the volume and ← and X buttons, as the index.html should, since they use the exact same Javascript.
I was able to find some workaround: creating one JavaScript file for each HTML page, this is redundant and non-optimal I know, but at least it works.
This also made me realize that the commented-out line was blocking the program because the index.html page doesn't use the previous_page button, that's what led me to make a JS file for each HTML page.
If anybody has any other suggestions I am all ears.
Edit: I reduced the number of JS scripts to only 2. One for the index.html and the other for the identically-structured html pages of the other questions.
I am attempting to create a method which achieves the following:
Implanting a string (For example: "TEST") into the body of an HTML page, every certain number of words (10 for instance). This problem is complicated by the fact that the word count must carry over between elements.
For example, the following HTML:
<body>
<h1>My Day at the Park</h1>
<p>I had a great day at the park today.</p>
<p>It was very fun, and I would like to go again soon.</p>
</body>
Should become:
<body>
<h1>My Day at the Park</h1>
<p>I had a great dayTEST at the park today.</p>
<p>It was very fun, and ITEST would like to go again soon.</p>
</body>
Accordingly, "TEST" was inserted after every 10th word ("day" and "I"). The first counted word is "My" and the last is "soon.".
A similar question has been asked in the past, though that question does not address the vital issue of continuity between elements (as mentioned in the comments by Oskar Lindberg).
My (failed) approach to solving this problem was by the following process:
1. Using jQuery $('body').text() to obtain all text in body. 2. Using .split(' ') to create array of all words. 3. Counting and recording every 10th word in a new array: cutoffWords[]. 4. Counting the number of times each cutoff word occurs before the occurance in which it is a cutoff word (10th word). 5. Running through $('body').html, and injecting the string after the cuttoff word on its cutoff occurance.
I can post the actual code, which is long, if requested, but this method suffers from an ihereint flaw, in that when running through $('body').html, text inside element tags are also counted, so that it can result in the misplacement of the string (or placement inside of an element tag).
As a novice JavaScript programmer I am at my whit's end, and will appreciate any advice.
I think the previous answer from Gerardo BLANCO is almost perfect. If you want to have some more control over the elements that are really handled (e.g., if a <script>-tag would appear in your code, it would also be counted) and if you want to also support nested elements, the following may help.
var validTypes = ['h1', 'p', 'div', 'span'];
var pos = 10;
var addedText = 'TEST';
var counter = 0;
var splitter = function ($el) {
$el.contents().each(function () {
var $innerEl = $(this);
if (this.nodeType === Node.TEXT_NODE) {
var text = $innerEl.text().trim();
if (text !== '') {
var content = text.replace(/ +/g, ' ').split(' ');
var newText = '';
for (var i = 0; i < content.length; i++) {
newText += ' ' + content[i];
if (++counter === pos) {
newText += addedText;
counter = 0;
}
}
this.nodeValue = newText;
}
} else if (this.nodeType === Node.ELEMENT_NODE &&
validTypes.indexOf(this.tagName.toLowerCase()) > -1) {
splitter($innerEl);
}
})
};
splitter($('body'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<h1>My Day at the Park</h1>
<script>// do nothing here just ignore me</script>
<p>I had a great day at <span style='color:red'>the</span> park today.</p>
<p>It was very fun, and I would like to go again soon.</p>
</div>
</body>
Awesome challenge
Ok lets start,
First of all i need to insert everything in a div because the scipts counted as the body children. If this doesnt work for you, we can make a work around.
I made a var current this var will keep count of how many words we have gone through
I get all the childrens div and loop between them. Then i split the childrens word and count them
If the count + current is bigger than 10, then we need to add an element.
If not, then current gets the count added
Hope this helps :)
let current = 0;
$('div').children().each(function() {
let words = $(this).text().split(" ");
if (current + words.length < 10) {
current += words.length;
} else {
let diff = 10 - current;
words[diff - 1] = words[diff - 1].concat("TEST");
this.innerHTML = words.join(" ");
current = words.length - diff;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div>
<h1>My Day at the Park</h1>
<p>I had a great day at the park today.</p>
<p>It was very fun, and I would like to go again soon.</p>
</div>
</body>
Watch and Learn
//<![CDATA[
/* external.js */
var doc, bod, M, I, S, Q, addTextAfterEvery, old = onload; // for use on other loads
onload = function(){
if(old)old(); // change old var name if using technique on other pages
doc = document; bod = doc.body;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
S = function(selector, within){
var w = within || doc;
return w.querySelector(selector);
}
Q = function(selector, within){
var w = within || doc;
return w.querySelectorAll(selector);
}
addTextAfterEvery = function(text, wordCount, withinSelector){
var wi = withinSelector || 'body';
var all = Q(wi+' *');
for(var i=0,e,aa=[],l=all.length; i<l; i++){
e = all[i]; aa.push(e.innerHTML.split(/(?!:\S)\s+(?!:\S)/));
}
for(var i=0,w=0,a,r=[],l=aa.length; i<l; i++){
a = aa[i];
for(var n=0,q=a.length; n<q; n++){
if(++w%wordCount === 0)a[n] += text;
}
r.push(a.join(' '));
}
for(var i=0; i<l; i++){
all[i].innerHTML = r[i];
}
}
addTextAfterEvery('TEST', 10, '.main');
}
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#ccc; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>addTextAfterEvery</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<h1>My Day at the Park</h1>
<p>I had a great day at the park today.</p>
<p>It was very fun, and I would like to go again soon.</p>
</div>
</body>
</html>
I would like to know what is wrong in my code.
I'd like to delete all "link" tags if there is within the attribute "rel = "stylesheet"
This is my HTML code
<html>
<head>
<title>teset</title>
<meta charset="utf-8" />
<meta name="description" content="test." />
<meta name="author" content="Me" />
<link rel="author" href="www.mysite.uk" />
<link rel="stylesheet" type="text/css" href="www.mysite.uk/css/style.css />
<link rel="stylesheet" type="text/css" href="www.mysite.uk/css/style2.css />
</head>
<script src = "deleteCSS.js"></script>
<body onload="noCSS()">
<p> test !!</p>
</body>
</html>
This is my JS called "deleteCSS.js"
function noCSS(){
//I save tag "link"
var CSSlink = document.getElementsByTagName("link");
var CSSatt = CSSlink.getAttribute("rel");
for (i=0; i < CSSlink.length; i++){
if (CSSatt[i] == "stylesheet"){
CSSlink[i].remove(); }
}
}
with jquery try this
$("link[rel='stylesheet']").remove();
http://jsfiddle.net/7Fcxx/
function noCSS() {
var links = document.getElementsByTagName("link");
for (var i = links.length - 1; i >= 0; --i) {
if (links[i].rel === "stylesheet") {
links[i].parentNode.removeChild(links[i]);
}
}
}
You have to check the rel attribute of each <link> in the loop;
You can remove them in a reversed order (when you remove links[0], links[1] takes the place of it and when you remove links[1] it actually removes the second one of the rest;
Or you can just use while (links.length) instead, and always remove links[0] (the first one of the rest).
If you want a pure JavaScript implementation:
(function() {
var links = document.getElementsByTagName('link');
for(var i=0; i<links.length; i++) {
links[i].getAttribute('rel') === 'stylesheet' && links[i].remove();
}
})();
Copy this to a file no-css.js and put it at the end of your HTML file.
Your code is not working because getElementsByTagName is returning a NodeList, so calling getAttribute('rel') of it will return an error TypeError: Object #<NodeList> has no method 'getAttribute'. So you have to iterate through all the links (nodes) and if they have the rel attribute set to stylesheet, remove them.
Hope this helps!
This is another JavaScript implementation:
function noCSS(){
var CSSlink = document.getElementsByTagName("link");
for (i=0; i < CSSlink.length; i++ )
{
if (CSSlink[i].getAttribute("rel") === "stylesheet")
{
CSSlink[i--].remove();
}
}
}
Make sure you enter the quotation marks at the end of the href tags like
href="www.mysite.uk/css/style.css"