How to specify javascript generated id using javascript / jQuery?

I count the number of p-tags in a particular div with individual identifiers, where p-tags and identifiers are randomly generated by php and in different quantities, but in the form of an ID pattern (otherUser1, otherUser2, otherUser3, etc.).

for (var i = 1; i <= numUsers; i++) { var tagId = '#otherUser' + i + ''; document.write(tagId); var userName = $(tagId).html(); document.write(userName); } 

when I document the userName variable entry above, it gives me a null value because simply inserting the tagId variable into jQuery brackets does not do the job. How to do it right? - I do not mind using javascript or jQuery, or that's fine.

+4
source share
1 answer

I tried this using jQuery . This works very well with my localhost. But, nevertheless, I do not solve your problem or not.

I implemented javaScript as:

  function submit(){ var numUsers=3; for (var i = 1; i <= numUsers; i++) { var tagId = '#otherUser' + i; var userName = $(tagId).text().toString(); $('#user').append("Username" + i + " : " + userName + "<br/>"); } } 

And your HTML code:

  <div id="otherUser1">userName1</div> <div id="otherUser2">userName2</div> <div id="otherUser3">userName3</div> <input type="button" value="Click Me!!" onclick="submit();"/> <div id="user"></div> 

The DIV is currently displayed. But instead, HTML will automatically create PHP DIV files that will not be displayed later.

I also created this fiddle . I do not know why this does not work, even if it is the same!

Please correct me if I'm wrong somewhere.

Thank you.

EDIT : maybe jsfiddle does not support functions, (so the remote function line from javaScript)! So, update the fiddle and it works correctly.

+3
source

Source: https://habr.com/ru/post/1339589/


All Articles