简体   繁体   中英

Remove hyperlink behaviour from child elements

I have an anchor tag inside which I append some divs through jQuery. I want that the 'hyperlink' effect of the parent <a> tag should not appear in the appended child elements.

How can we achieve this with jQuery or in some other way.

Here is the fiddle of what I want.

UPDATE: Most of the answers tell how to remove the click effect. Isn't there something that can prevent every default behavior of anchor tag from child elements?

FIDDLE

Ok. Here is some sample HTML

<a href="google.com" id="first">
    <div>
        <p>Blah</p>
    </div>
    <div>
        <p>Blah</p>
    </div>
    <div>
        <p>Blah</p>
    </div>
</a>

<a href="google.com" id="second">
    <div>
        <p>Blah 2</p>
    </div>
    <div>
        <p>Blah 2</p>
    </div>
    <div>
        <p>Blah 2</p>
    </div>
</a>

This CSS will remove the underscore, change the font color and the cursor

div{
    display: inline;
}

#second{
    text-decoration: none;
    color: #000;
    cursor: default;
}

The jquery removes the click event from the children

$('#second').children().each(function(){
    $(this).click(function(e){
        e.preventDefault();
    });
});

Update : Further to your comments, what you are trying to do is complicated and kind of weird. You say for some reason you have to wrap the divs in an achor tag but not have them inherit the properties. You will have to make some trade-off. The trick is to remove the 'href' from the a tag. You would not have to write any jQuery/javascript for this. As a matter of fact you don't even need any CSS then. Essentially, remove all the css and jquery from the above and remove the href from the second a.

FIDDLE

You can use the :first-child Selector. Look at http://api.jquery.com/first-child-selector/

You can remove underline with CSS:

a div {
    text-decoration: none
}

To stop anchor from following its href attribute you need to bind a handler to click event which returns false. In jQuery you can achieve it this way:

$('a div').on('click', function() {
    // do whatever you want to do here

    return false;
});

I edited selectors (added div ) after you provided jsfiddle. Still, there is one more thing. According to your fiddle I assume you didn't want "Something" to be wrapped with div. It should look like this: jsfiddle

You should add an eventlistener to your anchors and prevent the default behaviour:

document.getElementsByTagName("a")[0].addEventListener("click", function(e){
    if(e.target.tagName=="DIV") e.preventDefault();
});

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