Can I select only when there's no text around it?

前端 未结 4 961
执笔经年
执笔经年 2021-01-21 16:05

I would like to select anchor tags only when they\'re completely by themselves, that way I can make those look like buttons, without causing anchors within sentences to look lik

相关标签:
4条回答
  • 2021-01-21 16:18

    I don't think it's generally possible, but you can come close. Here are some helpful places to start:

    1. The Only Child Selector which would allow you to select all a elements which have no siblings like so a:only-child {/* css */}. See more here. (Also see edit)

    2. The Not Selector which would allow you to exclude some elements perhaps using something along the lines of :not(p) > a {/* css */} which should select all anchors not in a paragraph. See some helpful information here.

    3. Combining selectors to be as specific as possible. You might want all anchors not in an h1 and all anchors not in a p.

    Example:

    The final product might look like this:

    a:only-child, :not(p) > a {/* css */}
    

    This should select all anchors that are only children and anchors that are not in a paragraph.

    Final note:

    You may want to consider making the buttons actual button or input tags to make your life easier. Getting the HTML right first usually makes the CSS simpler.

    Edit: the only child ignores the text, so that's pretty much useless here. I guess it's less doable than I thought.

    0 讨论(0)
  • 2021-01-21 16:26

    The simple answer is: no, you can't.

    As explained here, here and here, there is no CSS selector that applies to the text nodes.

    If you could use jQuery, take a look at the contains selector.

    0 讨论(0)
  • 2021-01-21 16:32

    jQuery Code Example:

    // this will select '<p><a></a></p>' or '<p><a></a>text</p>'
    // but not '<p><a></a><a></a></p>'
    $('p').has('a:only-child').each(function() {
        const p = $(this); // jQuerify
        let hasalsotext = false;
        p.contents().each(function(){
            if ((this.nodeType === 3) && (this.nodeValue.trim() !== "")) {
                hasalsotext = true;
                return false; // break
            }
        });
        if (!hasalsotext) {
            $('a', p).addClass('looks-like-a-button');
        }
    });
    
    0 讨论(0)
  • 2021-01-21 16:38

    Unfortunately no, you can't.

    You have to use JS by it self or any librady of it to interact with content of elements and found where is each element in the content.

    If you wish me to update my answer with a JS example prease ask for it.

    0 讨论(0)
提交回复
热议问题