How do I look for a tag's ID using the known html content inside the tag using javascript or jQuery?
I have randomly generated number of tags开发者_StackOverflow社区 with patterened IDs (otherUser1, otherUser2, otherUser3, etc.) and the html content of the p tags with these IDs are usernames. I want to find the ID of the p tag with the correct username and was wondering how I do this. Below is the code I tried using but it returns the tagId of every single p tag even though only one of the p tags holds the userName I'm looking for (represented by the variable 'selectedUser').
var selectedUserName = $("#selectedUser a").html();
var numUsers = document.getElementById('otherUsers').getElementsByTagName('p').length;
for (var i = 1; i <= numUsers; i++) {
var tagId = '#otherUser' + i;
var userName = $(tagId).html();
if (selectedUserName = userName) {
document.write(tagId);
}
}
You have an assignment operator (=) instead of a comparison operator (==) in your if statement.
Strange mix of jQuery/standard JS in there :)
You're missing some ==
in your if statement. Should be:
if (selectedUserName === userName) {
document.write(tagId);
}
精彩评论