0

I am a C# developer. My clientside javascript skills are very low.

In javascript I have a string value. That contains the following:

<div id="foo" data-redirectURL="bar">
    <div>Lorem Ipsum</div>
</div>

How do I retrieve the value of data-redirectURL in this case: "bar" ?

4
  • Everyone who's answer this question, please notice that he said the HTML is in a string, not in the DOM. Commented Feb 20, 2017 at 16:47
  • Please show us the code in relevant context. Commented Feb 20, 2017 at 16:53
  • @Barmar Why did you delete your answer. Commented Feb 20, 2017 at 16:59
  • @Kinduser It didn't work. Commented Feb 20, 2017 at 17:17

3 Answers 3

2

Use attr like this:

var str = '<div id="foo" data-redirectURL="bar"><div>Lorem Ipsum</div></div>';

var value = $(str).attr("data-redirectURL");

console.log(value);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

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

2 Comments

I tested this code and it worked. So I accept this as the answer!
You took the effort to read my question. And provided the most simple and readable answer. Thank you!
1

You could adjust your data attribute and use data() :

$('#foo').data('redirect-url');

HTML :

<div id="foo" data-redirect-url="bar">
    <div>Lorem Ipsum</div>
</div>

Hope this helps.

DOM snippet :

console.log( $('#foo').data('redirect-url') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="foo" data-redirect-url="bar">
  <div>Lorem Ipsum</div>
</div>

String snippet :

var my_string = '<div id="foo" data-redirect-url="bar"><div>Lorem Ipsum</div></div>';

console.log( $(my_string).data('redirect-url') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 Comment

I have a string value, he said!
0

There is multiple ways of getting a data attribute value on

jquery: $('#foo').attr("data-redirectURL")

javascript: document.getElementById('foo').getAttribute('data-redirectURL');

console.log($('#foo').attr("data-redirectURL"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo" data-redirectURL="bar">
    <div>Lorem Ipsum</div>
</div>

4 Comments

with jquery you can just use $('#foo').data("redirectURL")
This searches the DOM, not a string.
@SteevePitis : please consider the fact that the HTML is a string ! It is not part of the DOM!
I have a string value, he said!

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.