1

I have a string that contains an HTML code snippet and I want to get the value of the id attribute from the element dt.

var myHtml = "<dt id='119'>Email</dt><dd id='container'>my text</dd>";

Expected result:

var myId = 119;

Does anyone have any ideas how I can do this?

4 Answers 4

3

Simply can use .attr()

var myHtml = "<dt id='119'>Email</dt><dd id='container'>my text</dd>";
var myId = $(myHtml).first().attr('id');
alert(myId);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

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

2 Comments

You should target the dt explicitly, in case other ids are added before the target id (or the order reversed), but yes this will work.
^ <dt> @TrueBlueAussie
2

You can wrap the string in jQuery and simply use attr

var myId = $(myHtml)
          .first() // get the first element - <dt>
          .attr("id"); // get the id

Note that you could just use attr since jQuery only gets the first attribute if multiple elements are involved, but using first is more semantic, or at least I think so.

1 Comment

@Brandao glad to have helped you
2

If the order of elements may be changed you should find the specific dt then gets its id attribute. attr(), by itself, will only return the first matching id found so is not a robust solution:

$(myHtml).filter('dt').attr('id')

You have to use filter(), and not find() as they are all top level elements in that HTML snippet.

http://jsfiddle.net/TrueBlueAussie/ghwzsao0/

The safer alternative, if the content can vary, is to wrap the html in another temp element that find() can be used with:

$('<div>').html(myHtml).find('dt').attr('id')

http://jsfiddle.net/TrueBlueAussie/ghwzsao0/1

Comments

1

You can test this in console:

$("<dt id='119'>Email</dt><dd id='container'>my text</dd>").eq(0).attr('id')

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.