简体   繁体   中英

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;
    });
});

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

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

$(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;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM