ladygeekgeek
ladygeekgeek

Reputation: 63

Target an element by its anchor title in javascript

I would like to hide the home menu item from my navigation menu and only display it when the mobile navigation menu is toggled. Is there a way that I can select the li item by anchor title (home) and add the active class to it when toggled, like I have done to the other elements? or could I do this with css somehow? I'm using a wordpress nav menu so I can't add a specific class to it. Many thanks.

    $(document).ready(function() {
    $('body').addClass('js');
    var $menu = $('#menu'),
    $logo = $('.logo'),
    $menulink = $('.menu-link');

    $menulink.click(function() {
    $menulink.toggleClass('active');
    $menu.toggleClass('active');
    $logo.toggleClass('active');
    return false;
    });
});

Upvotes: 3

Views: 2528

Answers (3)

eapo
eapo

Reputation: 1081

$(document).ready(function() {
    $('body').addClass('js');
    var $menu = $('#menu'),
    $logo = $('.logo'),
    $menulink = $('.menu-link');
    $homelink = $('li[title*="home"]'); // remove the * if u have more with "*home*"

    $menulink.click(function() {
        $menulink.toggleClass('active');
        $menu.toggleClass('active');
        $logo.toggleClass('active');
        $homelink.toggleClass('active');
        return false;
    });
});

Upvotes: 0

Milche Patern
Milche Patern

Reputation: 20462

You know you can target an anchor attributed of a title with only css ?

a[title^="Some title text"] { color: red; }

For targeting with javascript --> related

var links = top.document.getElementsByTagName('a'); var result = []; var linkcount = links.length; for ( var i = 0; i < linkcount; i++) { if (links[i].getAttribute('title') === 'some title text here') { result.push(links[i]); } }

For targeting with jQuery --> user John Conde answered before or Get element by title jQuery

$('a[title="Some title text"]')

Also, try a search on the net with your question --> google for an example

Upvotes: 2

John Conde
John Conde

Reputation: 219834

This will get the anchor with the title of "home"

$('a[title="home"]')

So you would use

$('a[title="home"]').toggleClass('active');

See the W3C selectors reference for more on this syntax

Upvotes: 6

Related Questions