0

I want to access only a name of the artist, in this case "Guns N Roses". I already have a solution: http://jsfiddle.net/QRBgp/4/

But I am interested is there any shorter way for this? Better way? I know some would say "if it works, why do you ask", but I am curious.

HTML:

<div id="now_playing" class="tab ui-tabs-panel ui-widget-content ui-corner-bottom">
<div class="banner"> … </div>
<div class="banner_wrap banner_top_left"></div>
<div class="banner_wrap banner_bottom_left"></div>
<div class="banner_wrap banner_top_right"></div>
<div class="banner_wrap banner_bottom_right"></div>
<div class="play-cont">
    <div class="curr-song-block clearfix">
        <div class="thumb"> … </div>
        <div class="descr">
            <em> … </em>
            <h3> … </h3>
            <div class="data-block">
                <div class="data">
                    <strong> by </strong>
   Guns N Roses
</div>
                <div class="data">
                  <strong> on </strong>
   Appetite for Destruction
</div>
                </div>
            </div><p> … </p>
        </div>
    </div>
    <div id="accordion" class="ui-accordion ui-widget ui-helper-reset" role="tablist"> … </div>
</div>

jQuery I used:

$( ".data-block" ).click(function() {
alert($('#now_playing').find('.descr').find('.data-block').find('.data:first-child').clone().children("strong").remove().end().text()); 
});
sensei
  • 7,044
  • 10
  • 57
  • 125
  • You may want to post this to http://codereview.stackexchange.com/ – Smeegs Aug 22 '13 at 14:47
  • [select deepest child in jQuery](http://stackoverflow.com/questions/3787924/select-deepest-child-in-jquery) - it is a similar problem. Hope it helps. – ksalk Aug 22 '13 at 14:48

3 Answers3

1

You can just use:

 alert($('#now_playing .data:first').text().replace(/\s+by\s+/,''));
 //or:
 alert($.trim($('#now_playing .data:first').contents()[2].textContent));

If you want shorter though, it would easier if you just used elements for your text nodes - it would make this job much easier. Such as $("#now_playing .artist_name").text()

MDEV
  • 10,730
  • 2
  • 33
  • 49
  • I am parsing this from the site I do not own, that's why I can't "refactor" HTML ;) Thank you I like your approach. – sensei Aug 22 '13 at 15:11
1

I'm curious why you wouldn't simply wrap the name in a <span /> and give it a class name. Then you could just select it by class. This makes your markup and code: a) more readable and understandable, and b) faster, because you don't have to clone() anything just to remove one word.

HTML

<div class="data">
  <strong>by</strong> <span class="artist">Guns n' Roses</span>
</div>

jQuery

#('#now-playing .descr .data:first-child').find('.artist').text();
Brett
  • 4,268
  • 1
  • 13
  • 28
1
$( ".data-block" ).click(function() {
alert($(this).('.data:first-child').clone().children("strong").remove().end().text());});
M.R
  • 466
  • 6
  • 14