I've encountered this problem while trying to append a list item to a class under a parent section which have an id name. So, assume that I have 2 sections with different ids. And I'd like to append message to the first section. Here is the HTML code.
<section id="to1" class="privateMsg">
<p class="toWho">To 1<a href="#" class="close">x</a></p>
<ul class="messages"> <!-- I want to grab this element -->
<li>...</li> <!-- so that I could append message here -->
</ul>
<form class="sendPMsg" action="/" method="post">
<input placeholder="Your message..." type="text">
<button name="send" type="button" class="sendPrivateBtn">Send</button>
</form>
</section>
<section id="to2" class="privateMsg">
<p class="toWho">To 2<a href="#" class="close">x</a></p>
<ul class="messages"> <!-- but not this one -->
<li>...</li>
</ul>
<form class="sendPMsg" action="/" method="post">
<input placeholder="Your message..." type="text">
<button name="send" type="button" class="sendPrivateBtn">Send</button>
</form>
</section>
How can I do this with javaScript? I have tried:
var idCheck = 'to'+frmUser;
var privateChatExist = document.getElementById(idCheck);
if ( privateChatExist != null) {
// this is where I have problem
$(".messages").append('<li><a class="user ' + frmUser + '" href="#">' + frmUser + '</a>: ' + msgContent + '</li></ul>');
}
else {
// add new section
}
but it appended to both sections, since they both have messages class. How should I go about this?
您可以将第一个选择器从$(".messages")
更改$("#" + idCheck + " .messages")
,这对于第一个id来说就像$("#to1 .messages")
$("#to2 .messages")
,依此类推
您需要将.message
选择器更具体地指向您希望它反映的部分。
$("#"+ idCheck + "> .messages")
Try replacing $(".messages")
with $("#" + idCheck + " > .messages")
. This will give you only elements with the class messages that are children of an element with the id of your idCheck variable. The >
character is used to perform a search only among immediate children of a specific node or nodes.
There's lots of other ways to limit results from jQuery selectors. See: How to select child elements under id in jQuery
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.