0

i style <a> with background color... but when i have <img> in the link tag, the background color is visible under/near/anywhere-of the image.

so, i would like to style those links which contain images (background: none) but as css4 parent-element does not show up yet in any browser (a < img). How can i do it with javascript ?

3
  • 1
    Have you tried anything yet? Commented Jan 3, 2014 at 14:44
  • So, any link that has an image should have no background? Commented Jan 3, 2014 at 14:51
  • @crush : yes, any link ! Lex Podgorny has answered here below, i use his jquery code which works... now, i just try to figure out how to disappear the bg color even before page loads (my question is in the comment of Lex Podgorny's answer) Commented Jan 3, 2014 at 15:38

2 Answers 2

2

With jquery you can do:

$('a:has(img)').css('background-color', 'transparent');

With straight up javascript I would try:

// Check not only immediate children but all descendants recursively
function hasImgChild(oElement) {
    if (oElement.tagName == 'img') { return true; }
    for (var n=0; n<oElement.childNodes.length; n++) {
        if (hasImgChild(oElements.childNodes[n])) { return true; }
    } 
    return false;
}

// Get all <a> tag dom references
var aLinks = document.getElementsByTagName('a');

// Loop through all <a> tags and if any of them
// Have <img> descendants, set background-color css property to 'transparent'
for (var n=0; n<aLinks.length; n++) {
    if (hasImgChild(aLinks[n])) {
        aLinks[n].style.backgroundColor = 'transparent';
    }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Why not use the built in .contains function?
@scrblnrd3 Please post a reference to .contains documentation and suggest where exactly I should use it.
Ok, thanks, jquery works... only one problem, the background colors disappear only after one second... i use $(document).ready(function(){, maybe is there another way that the colors do not appear even for a second ?
Then I would suggest doing the reverse. Instead of clearing bgcolor on ready, add it to elements that don't have the image inside. Of course, you'd have to edit your styles as well.
Like so: $('a:not(:has(img))').css('background-color', 'yellow');
|
0

With pure Javascript you can do

elements=document.getElementsByTagName("transparent");
for(var i=0;i<elements.length;i++){
    el=elements[i];
    if(el.contains("img")){
        el.style.backgroundColor="white";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.