Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

javascript - jQuery: Select data attributes that aren't empty?

I'm trying to select all elements that have a data-go-to attribute that is not empty.

I've tried $('[data-go-to!=""]') but oddly enough it seems to be selecting every single element on the page if I do that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just as further reference, and an up-to-date (may'14) (aug'15) (sep'16) (apr'17) (mar'18) (mar'19) (may'20)...
Answer that works with:

Empty strings:

If the attr must exist & could have any value (or none at all)

    jQuery("[href]");

Missing attributes:

If attr could exist & if exist, must have some value

    jQuery("[href!='']");

Or both:

If attr must exist & has to have some value...

    jQuery("[href!=''][href]");

PS: more combinations are possible...


Check this test in jsFiddle for examples:


Or here in SO with this Code Snippet.

* Snippet is running jQuery v2.1.1

jQuery('div.test_1 > a[href]').addClass('match');
jQuery('div.test_2 > a[href!=""]').addClass('match');
jQuery('div.test_3 > a[href!=""][href]').addClass('match');
div,a {
    display: block;
    color: #333;
    margin: 5px;
    padding: 5px;
    border: 1px solid #333;
}
h4 {
    margin: 0;
}
a {
    width: 200px;
    background: #ccc;
    border-radius: 2px;
    text-decoration: none;
}
a.match {
    background-color: #16BB2A;
    position: relative;
}
a.match:after {
    content: 'Match!';
    position: absolute;
    left: 105%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test_1">
    <h4>Test 1: jQuery('a[href]')</h4>
    <a href="test">href: test</a>
    <a href="#">href: #</a>
    <a href="">href: empty</a>
    <a>href: not present</a>
</div>
<div class="test_2">
    <h4>Test 2: jQuery('a[href!=""]')</h4>
    <a href="test">href: test</a>
    <a href="#">href: #</a>
    <a href="">href: empty</a>
    <a>href: not present</a>
</div>
<div class="test_3">
    <h4>Test 3: jQuery('a[href!=""][href]')</h4>
    <a href="test">href: test</a>
    <a href="#">href: #</a>
    <a href="">href: empty</a>
    <a>href: not present</a>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...