0

I want to get the href attr value based on the value of the rel attr . How do I do this in javascript?

<links>
    <link href="https://someurl/index/16380" rel="self"/>
    <link href="https://someurl/index/16380/streams?lang=en" rel="streams"/>
    <link href="https://someurl/index/16380/bif" rel="bif" />
</links>

something along the line ....

$(xml).find('link').each(function(){
 if(rel == 'streams'){
   this.streamurl = $(this).attr('href');
 }
});
6
  • 1
    $(this).attr('rel');, unless I'm missing something here? Commented Mar 5, 2014 at 15:52
  • So you want to know how to read the rel attribute? If so @ShadowWizard has your answer Commented Mar 5, 2014 at 15:54
  • @ShadowWizard, I want to get the value of href where rel="streams". $(this).attr('rel'); would just give me the value of rel. Commented Mar 5, 2014 at 15:56
  • 1
    Javascript ?? looks like you are using jQuery..\ Commented Mar 5, 2014 at 15:56
  • @Fabii right, so you need to compare $(this).attr('rel') with the value you want it to have. It's just really basic and you appear to be a decent programmer that's why I'm confused here. Commented Mar 5, 2014 at 16:01

2 Answers 2

4
$(xml).find("link[rel=streams]")
      .each(function(i,lnk) {
          lnk.streamurl = lnk.href; 
      })

Or

$(xml).find("link[rel=streams]")
      .prop("streamurl", function() {
          return this.href; 
      })

Your original code was almost correct. Just needed this:

if(this.rel == 'streams'){

instead of this:

if(rel == 'streams'){

Open your developer console, and you'd probably see something like:

ReferenceError: rel is not defined

Sign up to request clarification or add additional context in comments.

Comments

1
$(xml).find('link').each(function(){

  //prevents your re-wrapping this multiple times
  var $this = $(this);

  //read the attribute
  if($this.attr('rel') == 'streams'){
     this.streamurl = $this.attr('href');
  }
});

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.