最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Accessing inline CSS properties using getElementsByClassName - Stack Overflow

programmeradmin0浏览0评论

I have this piece of HTML code.

<div class="tagWrapper">
<i style="background-image: url(.jpg);"></i>
</div>

I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?

I have this piece of HTML code.

<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>

I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?

Share Improve this question edited Dec 17, 2011 at 19:16 ThinkingStiff 65.4k30 gold badges147 silver badges241 bronze badges asked Dec 17, 2011 at 17:32 IsuruIsuru 31.3k63 gold badges192 silver badges314 bronze badges 2
  • What browsers the code has to work with? – Michas Commented Dec 17, 2011 at 17:38
  • See this fiddle of my answer: jsfiddle/c4urself/8kj7b – c4urself Commented Dec 17, 2011 at 17:45
Add a ment  | 

7 Answers 7

Reset to default 2

You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):

var origUrl = document.getElementsByClassName("tagWrapper")[0]
                          .children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);

Or

var url = origUrl.replace("url(", "").replace(")", "");

Here's a fiddle

EDIT

Answering your ment

document.getElementsByClassName("tagWrapper")

gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index

document.getElementsByClassName("tagWrapper")[0]

Then you want the first child under there, and the backgroundImage property on this first child.

document.getElementsByClassName("tagWrapper")[0]
                          .children[0].style.backgroundImage;

From there it's a simple matter stripping the url( and ) from it

var url = origUrl.substr(4, origUrl.length - 5);

or

var url = origUrl.replace("url(", "").replace(")", "");

You can use querySelector():

Demo: http://jsfiddle/ThinkingStiff/gFy6R/

Script:

var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);

If you where using jquery you could do something like this

$(".tagWrapper i").css("background-image")

I think if you use jQuery it will be easer.

var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
  if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
    return w.childNodes[i].style.backgroundImage;
<div class="tagWrapper">
     <i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>

// script / without jQuery

var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];

Use jQuery!!!

$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)

Example

If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
    var do_find_a = function() {
        var tmp = document.getElementsByClassName('tagWrapper')[0];
        var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
        return do_alert(tst);
    }
    var do_find_b = function() {
        var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
        return do_alert(tst);
    }
    var do_alert = function(tst) {
        var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
        var ret = reg.exec(tst);
        alert (ret[1]);
        return;
    }
    document.addEventListener('DOMContentLoaded',do_find_a,false);
    document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
    <div class='tagWrapper'>
        <i style='background-image: url("http://example./image.jpg");'></i>
    </div>
    Text to ignore.
</body>
</html>

And jsFiddle version:
http://jsfiddle/hpgmr/

发布评论

评论列表(0)

  1. 暂无评论