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

Get id from string using javascript - Stack Overflow

programmeradmin3浏览0评论

I have this simple string:

<div id="parent">
     <div id="1" class="child">test</div>
</div>

How can I extract the id number (1) from this string?

I have this simple string:

<div id="parent">
     <div id="1" class="child">test</div>
</div>

How can I extract the id number (1) from this string?

Share Improve this question edited May 27, 2014 at 22:21 Michael Samuel asked May 27, 2014 at 22:15 Michael SamuelMichael Samuel 3,92012 gold badges51 silver badges86 bronze badges 3
  • Could you clarify what you mean by this HTML string? – Frédéric Hamidi Commented May 27, 2014 at 22:21
  • I mean this is a text string that is like HTML – Michael Samuel Commented May 27, 2014 at 22:23
  • Then the answer you received so far is invalid. Please post the code you're working with, so we can help more. – Frédéric Hamidi Commented May 27, 2014 at 22:24
Add a ment  | 

6 Answers 6

Reset to default 3

With JQuery you can

<script src="http://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  var str = $('<div id="parent"><div id="1" class="child">test</div></div>');
  console.log(str.find(':nth-child(1)').attr('id'));
</script>

Where nth-child is the target you want to get the id

var s = '<div id="parent"> <div id="1" class="child">test</div> </div>';

var d = new DOMParser().parseFromString( s, "text/xml" );

var id = d.firstChild.childNodes[1].attributes['id']; 

console.log( id );
var htmlString = '<div id="parent"><div id="1" class="child">test</div></div>';
var number = /id="(\d)"/.exec(htmlString)[1];

console.log(number); //outputs the number

You would have to do a match on the string object that the HTML is stored in. so, if the string is called htmlString, then you would do something akin to

var id = htmlString.match(/id=\"([0-9]+)\"/)

That SHOULD net you the result, but if you deal with any data that is more plex than the example you've been given, you would need a different regex.

<script>
 let num = document.getElementById('1')
 let ans = parseInt(num.id)
</script>

Although I am unsure as to what you are trying to acplish, one way of getting of doing this is s to gather all like tagnames ("div" in this case) into an array and select the array index you desire (1 in this case) then reference the id - as follows:

var list=document.getElementsByTagName("div")
alert(list[1].id);
发布评论

评论列表(0)

  1. 暂无评论