Swapping out a style sheet within a intricate header

I'm in search of help with creating a stylesheet switcher for my website. My knowledge of html/css/js is self-taught, so I ask for forgiveness for any beginner mistakes. I have customized some code to fit my requirements, but I am unsure how to target a specific line in the head section.

Here is the current code snippet:

<ul id="nav">
    <li><a href="#" rel="http://files.enjin.com/149304/theme-dark.css">Dark</a></li>
    <li><a href="#" rel="http://files.enjin.com/149304/theme-light.css">Light</a></li>
</ul>

<script>
$(document).ready(function() { 
    $("#nav li a").click(function() { 
        $("link").attr("href",$(this).attr('rel'));
        return false;
    });
});

$(document).ready(function() { 
    if($.cookie("css")) {
        $("link").attr("href",$.cookie("css"));
    }
    $("#nav li a").click(function() { 
        $("link").attr("href",$(this).attr('rel'));
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
        return false;
    });
});

$(document).ready(function() { 
    if($.cookie("css")) {
        $("link").attr("href",$.cookie("css"));
    }
    $("#nav li a").click(function() { 
        $("link").attr("href",$(this).attr('rel'));
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
        return false;
    });
});
</script>

Currently, this code changes all href links in the head section and causes issues with the page layout.

The specific href that requires modification (located on line 22) is as follows:

<link href="./Home - Oceanian Gaming Community_files/theme.php" media="screen" rel="stylesheet" type="text/css">

Any assistance on resolving this issue would be greatly valued.

Answer №1

Traversing DOM elements based on their line number in the source code is not possible.

To identify and modify the specific link tag you want, you can use a unique technique. One suggestion is to add a custom attribute to the element.

For example:

<link data-type="1" href="./Home - Oceanian Gaming Community_files/theme.php"  ... >

With this, you can easily select and manipulate the element using a selector.

$(document).ready(function() { 
    $("#nav li a").click(function() { 
        $("link[data-type='1']").attr("href", $(this).attr('rel'));
        return false;
    });
});

The above script is all you need for this purpose.


A slightly riskier approach would be to use the attribute-contains selector to target the specific link tag. Keep in mind that this method may match multiple elements depending on your page's content.

$("link[href*="/theme.php"]")

Update: upon further examination of the site:

After reviewing, there were a couple of errors in the previous solution.

Firstly, the quotes placement was incorrect - you should use $('link[href*="/theme.php"]') with single quotes outside and double quotes inside for the pattern (or vice versa).

Secondly, once you change the href attribute, the pattern href*="/theme.php" will no longer match. To address this, add a custom attribute when you first modify the href and then use this custom attribute to target the link tag subsequently.

if($('link[data-type]').length == 0) {
    // First modification - set href and add custom attribute
    $('link[href*="/theme.php"]').attr("href", $(this).attr('rel')).attr('data-type', 1);
}
else {
    // Subsequent modifications
    $('link[data-type]').attr("href", $(this).attr('rel')).attr('data-type', 1);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS Resizing the screen leads to misalignment of the footer layout

I am currently working on a page located at However, I have encountered an issue where the footer is not displayed properly when the screen size is changed. Below is the CSS code for the footer: #footer_1 { background: url("../images/bgfooter2.png") ...

Load data from a MySQL Database into a DataTable

I am currently in the process of developing a CRUD application. With a large dataset stored in a MySQL database, my intention is to utilize a JQuery DataTable instead of manually creating a table. However, the issue I am facing is that while the table appe ...

There was an issue encountered while attempting to utilize orgchart: The property '_aZ' of null could not be read

I've been exploring the use of an organization chart library from Everything goes smoothly with a few nodes, but when I attempt to load the entire organization (approximately 1100 subjects with multiple nested levels), I encounter this console error: ...

When attempting to preflight cross domain Ajax requests with a custom header using jQuery, the requests are consistently being terminated

I've been attempting to execute a cross domain POST request with custom headers, but the preflight is consistently being cancelled. I'm uncertain whether it's the browser or jQuery causing this cancellation as indicated in Chrome's "Ins ...

Stop the repetition of event handlers by utilizing the .off() method to remove duplicates

Here's a scenario where I've assigned two event handlers: $('#myElement').on('click', '.classA', doSomething); $('#myElement').on('click', '.classB', doSomethingElse); Now, the task at ...

Tips for ensuring a webpage loads at a specific resolution

I recently created a website on my computer with a screen resolution of 1920x1020. However, when I view it on other machines with a 1366x768 resolution, the website appears distorted. Is there a way to set a fixed resolution for my website to ensure it l ...

Loop through the last modified file

I am currently working on a webpage that displays the "last-modified" date of each file it loads: Have you noticed how the dates are loaded one by one as the page makes calls to the header? If not, try hitting F5 to refresh the page. Is there a way to im ...

use in jQuery.each

Is there a way to implement jQuery.each so that if a match is found within the array being processed, the iteration can be halted without processing the remaining elements? <ul> <li>foo</li> <li>bar</li> You can achieve thi ...

Is it possible to display a complete list of my items along with their parameters using jQuery ajax?

My function code is set up to display all the items from my list of discipline codes, but I'm facing issues viewing them due to data:{params} always being present. alert('Could not retrieve data'); Any assistance would be greatly appreci ...

Integrate, Delay, Experimentalize, and Attach components

This inquiry might lean more towards a general browser/javascript discussion rather than a focused prototype question, but I believe this community possesses a deep understanding of javascript and browsers. With that said, here is my query: If the followi ...

After refreshing the page, the ngRoute white page is displayed

I've encountered an issue with my Angular website. I built it using ngRoute, but when I click on a link, a white page appears. Only after refreshing the page does the content actually show up. Even in the browser's DevTools, you can see the html ...

Managing the Response from an Ajax Call

Currently, I am in the process of developing a user registration form for my website and have implemented ajax to manage server-side processes. My main issue lies in effectively handling the response generated by my PHP code. The potential responses from t ...

"Utilizing jQuery to add new items to a list using the

I'm a bit confused about the distinctions among these four lines of code: $('<li>').addClass('restaurant').appendTo('ul'); $('li').addClass('restaurant').appendTo('ul'); $('li& ...

There is a space separating the slider image and the navigation bar

Having a small space between the slider image and the navigation bar is causing some issues. I've tried various solutions like minifying the code, adjusting margins, and setting line heights to zero but nothing seems to be working. One question I have ...

Connecting a custom bootstrap stylesheet to WordPress

I'm having trouble linking my WordPress Stylesheet to a child theme in a different directory/subfolder. The code I placed in the functions.php file doesn't seem to be working correctly. Here is the code snippet: function theme_add_bootstrap() { ...

Leveraging JavaScript and HTML to extract a single data point from a JSON response

As a complete beginner, I want to clarify that I may not be using the correct terminology in my question. I am embarking on creating an HTML5/Javascript application with Intel XDK to retrieve barcode information for video games from an online API. Specifi ...

Utilize PHP's foreach loop to showcase information within multiple HTML div containers

I am presented with the following data and would like to showcase it in separate containers using HTML. Name Price Difference Signal CA.PA 15.85 3.5609257364073 MACD AZN.ST 896 3.4881049471963 MACD AMGN 258.57 1.6391533819031 SMA 50/ ...

Getting the chosen option from a dropdown list mapped in ReactJS

I am working on a dropdown select option that is linked to the data of an array object called 'template_titles'. Currently, the value in the dropdown corresponds to the title in the object. My goal is to be able to extract and use the selected va ...

Is there a way to shift the display of inline-block to the right?

I'm struggling with positioning a div that's nested within a display:inline-block. How can I align it to the right side of the container? <div style='width:100%'> left <div style='display:inline-block;position:relative;r ...

Issue with event listener arising once elements have been loaded into the dom

I have a project where I want to click on a category card to obtain its id and then redirect to the movies screen. I understand that using row.eventlistener() in index.js executes before the elements are rendered, causing the id not to be captured. How ca ...